home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1996 July: Mac OS SDK / Dev.CD Jul 96 SDK / Dev.CD Jul 96 SDK2.toast / Development Kits (Disc 2) / QuickDraw GX / Programming Stuff / Sample Code / Printing Samples / Printer Drivers… / ImageWriter / NewApp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-04-10  |  74.9 KB  |  2,655 lines  |  [TEXT/MPS ]

  1. /*
  2.     copyright © 1991-1994 Apple Computer Inc.  All rights reserved.
  3.     
  4.     NewApp.c
  5.     This file contains all new API implementations for the ImageWriter driver.
  6.     
  7.     Modification history
  8.     03/19/91        TED                New file today
  9.     04/23/91        Sam Weiss        Changed Inherit to Forward
  10.     05/29/91        TED                Added manual feed and faster mode support
  11.     12/20/93        dmh                Sync'd with the shipping 1.0b3 GX driver.
  12.     03/24/94        Ken Hittleman    Updated manual feed to use gxTrayFeedInfo
  13.     03/30/94        Ken Hittleman    Added call to paper matching CheckStatus when switching to auto-feed
  14.     07/05/94        Ken Hittleman    Removed set color and page size from IW I path, which blew cookies on it
  15.     08/26/94        dmh                Sync'd with the shipping 1.0.1 GX driver.
  16. */
  17.  
  18. #include <memory.h>
  19. #include <Errors.h>
  20. #include <ToolUtils.h>
  21. #include <Resources.h>
  22. #include <Packages.h>
  23. #include <PrintingDrivers.h>
  24. #include <PrintingMessages.h>
  25. #include <PrintingManager.h>
  26. #include <FixMath.h>
  27. #include <math routines.h>
  28. #include <math types.h>
  29. #include <Graphics Routines.h>
  30. #include <graphics libraries.h>
  31. #include <font library.h>
  32. #include <layout routines.h>
  33. #include <GXExceptions.h>
  34. #include <PrintingLibraries.h>
  35.  
  36. #include "CommonDefines.h"
  37.  
  38. /* ------------------------------------------------------------------------------------    */
  39. /*    INTERNAL DEFINES                                                                    */
  40. /* ------------------------------------------------------------------------------------    */    
  41.  
  42. // positive error for aborting job and placing on hold
  43. #define kPutJobOnHoldErr            3
  44.  
  45. // timeout (in ticks) for the initial query
  46. #define kQueryTimeout                (7*60);
  47.  
  48. // things this specific driver puts into the DTP config file
  49. #define    kImageWriterConfigType        'ifig'
  50. #define kImageWriterConfigID        (0)            
  51. typedef struct
  52.     {
  53.         Boolean    hasColorRibbon;
  54.         Boolean    hasSheetFeeder;
  55.         Boolean    isImageWriterII;        // is this an ImageWriter II, or an older model?
  56.     } ImageWriterConfigRecord, *ImageWriterConfigPtr, ** ImageWriterConfigHandle;
  57.     
  58. /* Define special characters needed */
  59. #define ESCAPE                (char) 27
  60.  
  61. /* A record to hold a set margins command */
  62. typedef struct SetMarginsRecord
  63.     {
  64.     char        cEscape;                    // ESCAPE character
  65.     char        cCommand;                    // Set Margins command character
  66.     char        cIndentDistance[4];            // number of dots to indent
  67.     } SetMarginsRecord, *SetMarginsPtr;
  68. #define kSetMarginsCommand    (char)'F'        // ImageWriter II uses 'F' for tabbing
  69. #define kSetMarginsSize        6
  70.  
  71. /*     Define a record that can hold one scan line's worth of data, 1280 will
  72.     only happen at 160 dpi. and 14 inch wide paper.   */
  73. typedef struct ScanLineRecord
  74.     {
  75.     char            cColorEscape;                    // ESCAPE character
  76.     char            cSetColorCommand;                // Set color command
  77.     char            cColor;                            // The color
  78.     char            cEscape;                        // ESCAPE character
  79.     char            cCommand;                        // 'enter graphics' command
  80.     char            cLineLength[4];                    // number of dots to print
  81.     char            iTheData[2240];                    // Bits for the data, enough for one line's worth
  82.     } ScanLineRecord, *ScanLinePtr;
  83. #define kGraphicsCommand    (char)'G'        /* graphics printing command */
  84. #define kRepeatGroup        (char)'V'        /* repeat group character */
  85. #define kSetColorCommand     (char)'K'        /* Set color command */
  86. #define kGroupSize            6                /* Size of one group header */
  87.  
  88. #define kScanLineSize         3                /* NOTE: this is just the header size! */
  89.  
  90. #define kStatusCommand        "\033?"            /* request device status/config */
  91.  
  92. // Status flags for PAP status queries
  93. #define    kColorRibbonBit        0
  94. #define kSheetFeederBit        1
  95. #define kPaperOutBit        2
  96. #define kCoverOpenBit        3
  97. #define kOffLineBit            4
  98. #define kPaperJamBit        5
  99. #define kPrinterFaultBit    6
  100. #define kHeadMovingBit        7
  101. #define kPrinterBusyBit        8
  102.  
  103. #define kOutOfPaperMask            (  (0x8000 >> kPaperJamBit) | (0x8000 >> kCoverOpenBit) | (0x8000 >> kOffLineBit) )
  104. #define kPrinterOfflineMask        (  (0x8000 >> kOffLineBit) )
  105. #define kPrinterBusyMask        (  (0x8000 >> kPrinterBusyBit) )
  106. #define kHeadMovingMask            (  (0x8000 >> kHeadMovingBit) )
  107.  
  108. //<FF>
  109. /* ------------------------------------------------------------------------------------    */
  110. /*    INTERNAL ROUTINES                                                                */
  111. /* ------------------------------------------------------------------------------------    */
  112. void Long2Dec(long aLong, Ptr emitHere)
  113. /*
  114.     Converts a long into an ASCII string, padded with leading zeros.
  115. */
  116. {    
  117.     char    aString[10];
  118.     short    i, actualWidth, strLength;
  119.     
  120.     NumToString(aLong, aString);
  121.     
  122.     // Get the width of the string, check for being too small
  123.     strLength = aString[0];
  124.     actualWidth = strLength;
  125.     if (actualWidth < 4)
  126.         actualWidth = 4;
  127.         
  128.     // output the string, padding with the requested character
  129.     strLength = actualWidth-strLength;
  130.     for (i = 0; i < actualWidth; ++i)
  131.         {
  132.         *emitHere++ = (i < strLength) 
  133.             ? '0' : aString[(i+1)-(strLength)];
  134.         }
  135.         
  136. } // Long2Dec
  137.  
  138.  
  139. //<FF>
  140. /* ------------------------------------------------------------------------------------    */
  141. Boolean PrinterHasColorRibbon(gxPrinter thePrinter)
  142. /*
  143.     Returns true if the config file says that the printer is blessed with a color ribbon,
  144.     false if it is a black and white ribbon.
  145. */
  146. {
  147.     Boolean                        hasColor = true;
  148.     Str32                        deviceName;
  149.     OSErr                        anErr;
  150.     ImageWriterConfigHandle        configHandle;
  151.     
  152.     // if not formatting to a particular device, assume color ribbon, for widest range of colorSpaces
  153.     GXGetPrinterName(thePrinter, deviceName);
  154.     if (deviceName[0] != 0)
  155.         {
  156.         // if we are going to a particular device, assume no color, as that is more common
  157.         hasColor = false;
  158.         
  159.         anErr = GXFetchDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, &(Handle)configHandle);
  160.         if (anErr == noErr)
  161.             {
  162.             hasColor = (**configHandle).hasColorRibbon;
  163.             DisposHandle((Handle) configHandle);
  164.             }
  165.         }
  166.     
  167.     return(hasColor);
  168.     
  169. } // PrinterHasColorRibbon
  170.  
  171.  
  172. //<FF>
  173. /* ------------------------------------------------------------------------------------    */
  174. gxViewDevice    NewDeviceResolutionViewDevice(void)
  175. /*
  176.     This routine creates a viewDevice and gives it a scale factor in it's mapping
  177.     appropriate for this device (144 dpi in the case of the IW)
  178. */
  179. {
  180.     gxViewDevice        vd;
  181.     
  182.     // create the viewDevices with a fake bitmap
  183.     {
  184.     gxShape        tempBitmap;
  185.     gxBitmap        aBitmap;
  186.     
  187.     aBitmap.pixelSize     = 1;
  188.     aBitmap.rowBytes     = 0;
  189.     aBitmap.width         = 0;
  190.     aBitmap.height         = 0;
  191.     aBitmap.image         = (char*)gxMissingImagePointer;
  192.     aBitmap.space         = gxNoSpace;
  193.     aBitmap.set         = nil;
  194.     aBitmap.profile     = nil;
  195.     
  196.     tempBitmap = GXNewBitmap(&aBitmap, nil);
  197.     vd = GXNewViewDevice(gxScreenViewDevices, tempBitmap);
  198.     GXDisposeShape(tempBitmap);
  199.     }
  200.  
  201.     // setup a mapping for a 144 (2X) viewDevice
  202.     {
  203.     gxMapping    vdMapping;
  204.     
  205.     ResetMapping(&vdMapping);
  206.     ScaleMapping(&vdMapping, ff(2), ff(2), ff(0), ff(0));
  207.     
  208.     GXSetViewDeviceMapping(vd, &vdMapping);
  209.     }
  210.     
  211.     return(vd);
  212.     
  213. } // NewDeviceResolutionViewDevice
  214.  
  215. //<FF>
  216. /* ------------------------------------------------------------------------------------    */
  217. Boolean    JobIsBest(long *imagewriterOptions)
  218. /*
  219.     Returns true if the current job is a final quality mode job, else returns false.
  220.     Also, returns the imagewriter rendering options.
  221. */
  222. {
  223.     Boolean            isFinal;
  224.     gxQualityInfo    jobQualitySettings;
  225.     long            itemSize = sizeof(jobQualitySettings);
  226.     OSErr            status;
  227.     Collection        jobCollection;
  228.     
  229.     // cache the collection
  230.     jobCollection = GXGetJobCollection(GXGetJob());
  231.     
  232.     // find out the info
  233.         
  234.     isFinal = false;
  235.     
  236.     status = GetCollectionItem(jobCollection, 
  237.                                     gxQualityTag, gxPrintingTagID, 
  238.                                     &itemSize, &jobQualitySettings);
  239.     
  240.     if ( (status == noErr) && (jobQualitySettings.currentQuality == (jobQualitySettings.qualityCount-1)) )
  241.         isFinal = true;
  242.     
  243.     ncheck( status );
  244.  
  245.     // we default to super res
  246.     *imagewriterOptions = kSuperRes;
  247.     itemSize = sizeof(imagewriterOptions);
  248.     status = GetCollectionItem(jobCollection, 
  249.                                     DriverCreator, 0, 
  250.                                     &itemSize, imagewriterOptions);
  251.                 
  252.     // and return the job quality mode
  253.     return(isFinal);
  254.     
  255. } // JobIsBest
  256.  
  257.  
  258. //<FF>
  259. /* ------------------------------------------------------------------------------------    */
  260.  
  261. OSErr    DoTheQuery(unsigned short * statusReturn, Boolean papStatus)
  262. /*
  263.     Returns in statusString the current status for the printer.  Returns various
  264.     errors from IO package if the printer's status could not be found.
  265. */
  266. {
  267.     OSErr                anErr = noErr;
  268.     long                statusLength;                    // status string size
  269.     SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  270.  
  271.     // default to a clear status
  272.     *statusReturn = 0;
  273.  
  274.     // send the query
  275.     if (papStatus)
  276.         {
  277.         char    statusString[255];                // returned string
  278.         
  279.         // According to the old IW driver, sometimes it will return all of the bits
  280.         // set.  This is an error, but we can just try again.
  281.         do {
  282.             statusLength = 255;
  283.             anErr = Send_GXGetDeviceStatus(nil, 0, statusString, &statusLength, nil);
  284.             } while ( (anErr == noErr) && (statusString[0] == 0xFF) );
  285.         
  286.         // return the printer status bits in the PAP case
  287.         *statusReturn = *(unsigned short*)&statusString[0];
  288.         }
  289.     else
  290.         {
  291.         char    statusString[8];                // returned string
  292.  
  293.         if ((**hGlobals).isImageWriterII)
  294.             {
  295.             statusLength = 8; // max number of characters to get back
  296.             anErr = Send_GXGetDeviceStatus(kStatusCommand, 2, statusString, &statusLength, "\p\n");
  297.                 
  298.             if ( anErr == gxAioTimeout)
  299.                 {
  300.                 *statusReturn = kPrinterOfflineMask;
  301.                 anErr = noErr;
  302.                 }
  303.             else
  304.                 {
  305.                 if (anErr == noErr)
  306.                     {
  307.                     // generate printer status bits in the serial case
  308.                     if (statusString[4] == 'C')
  309.                         *statusReturn |= 0x8000 >> kColorRibbonBit;
  310.                     if ( (statusString[5] == 'F') || (statusString[4] == 'F') )
  311.                         *statusReturn |= 0x8000 >> kSheetFeederBit;
  312.                     }
  313.                 }
  314.             }
  315.         }
  316.         
  317.     nrequire(anErr, Send_GXGetDeviceStatus);
  318.  
  319. // FALL THROUGH EXCEPTION HANDLING    
  320. Send_GXGetDeviceStatus:
  321.     
  322.     return(anErr);
  323.  
  324. } // DoTheQuery
  325.  
  326. //<FF>
  327. /* ------------------------------------------------------------------------------------    */
  328. OSErr FetchStatusString(unsigned short * statusReturn, Boolean papStatus, Boolean doRetry)
  329. /*
  330.     Returns in statusString the current status for the printer.  Returns various
  331.     errors from IO package if the printer's status could not be found.
  332.     
  333.     Handles reporting error conditions to the user.
  334. */
  335. {
  336.     OSErr            anErr;
  337.     SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  338.     
  339.     anErr = DoTheQuery(statusReturn, papStatus);        
  340.     nrequire(anErr, Send_GXGetDeviceStatus);
  341.     
  342.     // printer offline?
  343.     if (     
  344.         (doRetry) &&
  345.         ( ((*statusReturn) & kPrinterOfflineMask) != 0 )  
  346.         )
  347.         {
  348.         gxStatusRecord        theStat;
  349.         gxStatusRecord        *pStat = &theStat;
  350.         Boolean                printerIsFixed = false;
  351.         
  352.         pStat->statusOwner    = 'drvr';
  353.         pStat->statResId     = kDriverStatus;        
  354.         pStat->statResIndex = kCheckOnline;            
  355.         pStat->bufferLen      = 0;
  356.         pStat->dialogResult = nil;
  357.         
  358.  
  359.         // keep sending the user the alert until either
  360.         //  a) the problem resolves itself
  361.         //  b) the user responds via the dialog
  362.         //  c) some other (fatal) error happens
  363.         do
  364.             {
  365.             
  366.             // tell the user
  367.             anErr = GXAlertTheUser(pStat);
  368.             
  369.             // based on the user's response, continue or cancel
  370.             switch (pStat->dialogResult)
  371.                 {
  372.                 case ok:
  373.                     // retry
  374.                     break;
  375.                     
  376.                 case cancel:
  377.                     anErr = gxPrUserAbortErr;
  378.                     break;
  379.                     
  380.                 case 3:
  381.                     anErr = kPutJobOnHoldErr;
  382.                     break;
  383.                 }
  384.                 
  385.             // error to return from next idle
  386.             (**hGlobals).idleError = anErr;
  387.  
  388.             // if printer got suddenly turned online, do an OK
  389.             if ( (anErr == noErr) && ((papStatus) || (pStat->dialogResult == ok)) )
  390.                 {
  391.                 pStat->dialogResult = nil;
  392.                 (void) DoTheQuery(statusReturn, papStatus);        
  393.                 if (     
  394.                     ( ((*statusReturn) & kPrinterOfflineMask) == 0 ) 
  395.                     )
  396.                     {
  397.                     printerIsFixed = true;
  398.                     pStat->dialogResult = ok;
  399.                     anErr = noErr;
  400.                     }
  401.                 }
  402.                 
  403.             } while ((anErr == noErr) && (pStat->dialogResult == nil));
  404.  
  405.         // printer is okay -- no error
  406.         if (printerIsFixed)
  407.             anErr = noErr;
  408.         
  409.         // display "sending data to the printer" message
  410.         if (anErr == noErr)
  411.             anErr = GXReportStatus(kDriverStatus, kSendingData);
  412.         }
  413.  
  414. // FALL THROUGH EXCEPTION HANDLING    
  415. Send_GXGetDeviceStatus:
  416.     
  417.     return(anErr);
  418.     
  419. } // FetchStatusString
  420.  
  421. //<FF>
  422. /* ------------------------------------------------------------------------------------    */
  423. OSErr UpdateConfiguration(void)
  424. /*
  425.     This routine queries the printer for its hardware configuration (color ribbon and
  426.     sheet feeder options), and stores that info into the configuration file.
  427. */
  428. {
  429.     SpecGlobalsHdl                 hGlobals = GetMessageHandlerInstanceContext();
  430.     Str32                        deviceName;
  431.     OSErr                        anErr = noErr;
  432.     ImageWriterConfigHandle        configHandle;
  433.     ImageWriterConfigPtr        configPtr;
  434.     Boolean                        isImageWriterII = false;
  435.     ResType                        commType;
  436.     
  437.         
  438.     // find out what we are printing to, and how we are connected
  439.     GXGetPrinterName(GXGetJobOutputPrinter(GXGetJob()), deviceName);
  440.     anErr = GXFetchDTPData(deviceName, gxDeviceCommunicationsType, gxDeviceCommunicationsID, (Handle*)&configHandle);
  441.     nrequire(anErr, FetchCommType);
  442.     commType = **(ResType**)configHandle;
  443.     DisposHandle((Handle) configHandle);
  444.     
  445.     
  446.     // store away the communications type for future use
  447.     {
  448.     SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  449.     
  450.     (**hGlobals).commType = commType;
  451.     }
  452.     
  453.     // find out the original configuration
  454.     if (GXFetchDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, (Handle*)&configHandle) == noErr)
  455.         {
  456.         // remember if we thought we had an IW2 when we started
  457.         configPtr = *configHandle;
  458.         (**hGlobals).isImageWriterII = isImageWriterII = configPtr->isImageWriterII;
  459.         DisposeHandle((Handle) configHandle);
  460.  
  461.         // if we aren't an ImageWriter II, bail out now - because the timeout takes two minutes!
  462.         if (!isImageWriterII)
  463.             return(noErr);            
  464.         }
  465.     else
  466.         {        
  467.         // if we don't know yet, assume IW2 for PAP else Serial
  468.         if (commType == 'PPTL')
  469.             isImageWriterII = true;
  470.             
  471.         // Assume IW 2 so we do the query for real
  472.         (**hGlobals).isImageWriterII = true;
  473.         }
  474.         
  475.     // make a handle to hold our configuration information for the printer
  476.     configHandle = (ImageWriterConfigHandle) NewHandle(sizeof(ImageWriterConfigRecord) );
  477.     anErr = MemError();
  478.     nrequire(anErr, NewHandle);
  479.     
  480.     // setup the default for the device - in case the query fails
  481.     configPtr = *configHandle;
  482.     configPtr->hasColorRibbon = false;
  483.     configPtr->hasSheetFeeder = false;
  484.     configPtr->isImageWriterII = true;
  485.     
  486.     // send initial data first to make sure IO handshaking is working,
  487.     // to load the first sheet of paper into the feeder (if any),
  488.     // and to take up "gear lash" in the device.  This is copied from
  489.     // what the old driver did.  Not doing this will cause the sheet
  490.     // feeder not to feed the initial page of data.
  491.     {
  492.     char    sendBuffer[11];
  493.     
  494.     // <CR>
  495.     sendBuffer[0] = 0x0D;
  496.     
  497.     // linefeed size = 18/144th
  498.     sendBuffer[1] = ESCAPE;
  499.     sendBuffer[2] = 'T';
  500.     sendBuffer[3] = '1';
  501.     sendBuffer[4] = '8';
  502.     
  503.     // reverse line feed
  504.     sendBuffer[5] = ESCAPE;
  505.     sendBuffer[6] = 'r';
  506.     sendBuffer[7] = 0x0A;
  507.     
  508.     // forward line feed
  509.     sendBuffer[8] = ESCAPE;
  510.     sendBuffer[9] = 'f';
  511.     sendBuffer[10] = 0x0A;
  512.     
  513.     anErr = Send_GXWriteData(sendBuffer, 11);
  514.     nrequire(anErr, Failed_SendInitialData);
  515.     }
  516.     
  517.     {
  518.     unsigned short    statusReturn;
  519.     
  520.     // query the device
  521.     if ((isImageWriterII) && (commType == 'SPTL') )
  522.         (**hGlobals).idleTimeout = TickCount() + kQueryTimeout;
  523.     anErr = FetchStatusString(&statusReturn, (commType == 'PPTL'), isImageWriterII);
  524.     if ( (anErr == noErr) && ( (statusReturn & kPrinterOfflineMask) != 0 )  )
  525.         anErr = gxAioTimeout;
  526.     (**hGlobals).idleTimeout = 0;
  527.     (void) GXReportStatus(kDriverStatus, kSendingData);
  528.     
  529.     // and scan the string looking for information about printer kind and options
  530.     configPtr = *configHandle;
  531.     if ( anErr == gxAioTimeout )
  532.         {
  533.         // if we timeout and we don't know the printer kind - assume IW1
  534.         if (!isImageWriterII)
  535.             {
  536.             anErr = noErr;
  537.             isImageWriterII = configPtr->isImageWriterII = false;
  538.             }
  539.         }
  540.     else
  541.         {
  542.         isImageWriterII = true;
  543.         configPtr->hasColorRibbon = (statusReturn & (0x8000 >> kColorRibbonBit)) != 0;
  544.         configPtr->hasSheetFeeder = (statusReturn & (0x8000 >> kSheetFeederBit)) != 0;
  545.         }
  546.     nrequire(anErr, FetchStatusString);
  547.     }
  548.     
  549.     // Remember if this was an ImageWriter II after the query
  550.     (**hGlobals).isImageWriterII = isImageWriterII;
  551.     
  552.     // write out the new configuration
  553.     anErr = GXWriteDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, (Handle)configHandle);
  554.     
  555.     
  556. // CLEANUP EXCEPTION HANDLING
  557. FetchStatusString:
  558. Failed_SendInitialData:
  559.     DisposHandle((Handle) configHandle);
  560.     
  561. NewHandle:
  562. Send_GXWriteData:
  563. FetchCommType:
  564.     return(anErr);
  565.     
  566. } // UpdateConfiguration
  567.  
  568.  
  569. /* ------------------------------------------------------------------------------------    */
  570. OSErr WriteDraftChars(long **draftTable, unsigned char *draftChar, long numChars)
  571. /*
  572.     This routine writes out a single character in the native set of the printer.
  573.     It uses a table that's part of the driver to do the right thing in order to generate this
  574.     character.
  575. */
  576. {
  577.     OSErr        anErr = noErr;
  578.     char        outputChars[20];                // a maximum of 20 characters can be generated
  579.     short        charCount;                    
  580.     
  581.     // For each character in the buffer, determine how to map the character to a draft character
  582.     for (; numChars > 0; --numChars, ++draftChar)
  583.     {
  584.         // No characters yet for this output character
  585.         charCount = 0;
  586.             
  587.         // Only consider characters in the printable range
  588.         if (*draftChar >= 0x20)
  589.         {
  590.             unsigned long    draftControl = (*draftTable)[*draftChar-0x20];    // Fetch native mode long word corresponding to this character
  591.             unsigned char    outChar;
  592.             unsigned char    nationalSet;
  593.             short                i;
  594.             
  595.             // For each word which composes the native mode long word 
  596.             for (i = 1; i >= 0; --i)
  597.             {
  598.                 // Should we send a backspace character (to overstrike)?
  599.                 if ( (draftControl & 0x80000000) != 0 )
  600.                     outputChars[charCount++] = 0x08;
  601.                 
  602.                 outChar = (draftControl >> 16) & 0xFF;
  603.                 if (outChar != 0)
  604.                 {
  605.                     // Determine the national character set to select
  606.                     nationalSet = (draftControl >> 24) & 0xF;    
  607.     
  608.                     //    Is this character in the standard, built-in character set?
  609.                     if (nationalSet == 0)
  610.                     {
  611.                         outputChars[charCount++] = outChar;
  612.                     }
  613.                     else    //    T => Must select a foreign language character set 
  614.                     {
  615.                         outputChars[charCount++] = 0x1B;
  616.                         outputChars[charCount++] = 0x44;
  617.                         outputChars[charCount++] = nationalSet;
  618.                         outputChars[charCount++] = 0x00;
  619.                         outputChars[charCount++] = outChar;
  620.                         outputChars[charCount++] = 0x1B;                // We always switch back to the kAmerican character set
  621.                         outputChars[charCount++] = 0x5A;
  622.                         outputChars[charCount++] = 0x07;
  623.                         outputChars[charCount++] = 0x00;
  624.                     }
  625.                 }
  626.                 
  627.                 // Take the next (low) word and process it (if we're not all done)
  628.                 draftControl <<= 16;
  629.             }    
  630.         }
  631.             
  632.         // If we generated any data, send it out now
  633.         if (charCount > 0)
  634.             anErr = Send_GXBufferData(outputChars, charCount, gxNoBufferOptions);
  635.     }
  636.         
  637.     return(anErr);    
  638.     
  639. } // WriteDraftChars
  640.  
  641. /* ------------------------------------------------------------------------------------    */
  642. OSErr GetPointerThisBig(Ptr *theBuff, long numBytes) 
  643. {
  644.     OSErr        anErr = noErr;
  645.     
  646.     if (*theBuff != nil)
  647.     {
  648.         if ( GetPtrSize(*theBuff) < numBytes )    //    T => Won't be big enough; make a new one
  649.         {
  650.             DisposPtr(*theBuff);
  651.             *theBuff = nil;
  652.         }
  653.     }
  654.  
  655.     if (*theBuff == nil)
  656.     {
  657.         *theBuff = NewPtrClear(numBytes);
  658.         anErr = MemError();
  659.     }
  660.     
  661.     return(anErr);
  662.     
  663. } // GetPointerThisBig
  664.  
  665. /* ------------------------------------------------------------------------------------    */
  666. OSErr GetTextAndPosition(    gxShape            theShape, 
  667.                             Ptr                *theChars, 
  668.                             long            *numChars, 
  669.                             gxPoint            *textPosition)
  670. {
  671.     OSErr        anErr = noErr;
  672.     long        textLength;
  673.     
  674.     // Determine the size of the text data and the position of the text
  675.     textLength = GXGetLayout(theShape, nil, nil, nil, nil, nil, nil, nil, nil, textPosition);
  676.  
  677.     // Make sure we have a buffer pointer large enough to hold all of the data
  678.     
  679.     anErr = GetPointerThisBig(theChars, textLength);
  680.     require(anErr == noErr, CantAllocTextBuff);
  681.     
  682.     // Now we retrieve the text
  683.     GXGetLayout(theShape, *theChars, nil, nil, nil, nil, nil, nil, nil, nil);
  684.     
  685.     // Remember the number of characters in the shape
  686.     *numChars = textLength;
  687.     
  688.  
  689. /******* Clean-up *******/
  690.  
  691. CantAllocTextBuff:
  692.     return(anErr);
  693.     
  694. } // GetTextAndPosition
  695.  
  696. /* ------------------------------------------------------------------------------------    */
  697. OSErr PrintPageInDraftMode(gxShape thePage, gxRasterImageDataHdl imageData)
  698. {
  699.     OSErr                    anErr = noErr;
  700.     long                    i;
  701.     long                    numItems;
  702.     Fixed                    currYPos = ff(0);
  703.     Ptr                        theChars = nil;
  704.     long                    numChars = 0;
  705.     gxPoint                    textPosition;
  706.     Fixed                    oldTextSize = ff(0);
  707.     SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  708.     
  709.     // Since the page picture we need to process is a picture shape that's embedded in
  710.     // thePage (a shape containing one item => a picture), we need to extract the real
  711.     // page picture from thePage.
  712.     
  713.     thePage = GetPictureItem(thePage, 1, nil, nil, nil, nil);
  714.     numItems = GXGetPicture(thePage, nil, nil, nil, nil);
  715.     
  716.     // For each shape within the picture, check its type and process it accordingly
  717.     
  718.     for (i = 1; i <= numItems; ++i)
  719.     {
  720.         gxShape                theShape;
  721.         short                theType;
  722.                 
  723.         theShape = GetPictureItem(thePage, i, nil, nil, nil, nil);
  724.         theType = GXGetShapeType(theShape);
  725.         
  726.         if (theType == gxLayoutType)    //    T => We have a layout shape
  727.         {
  728.             fixed        textSize;
  729.             char        buff[12];
  730.             char        theFace;
  731.             short        cmndBuffSz;
  732.             
  733.             // First determine the style in which we're printing
  734.             
  735.             theFace = GetStyleCommonFace( GXGetShapeStyle(theShape) );
  736.             
  737.             buff[0] = ESCAPE;
  738.             if ( (theFace & bold) != 0 )    //    T => Turn bold facing on
  739.                 buff[1] = '!';
  740.             else                                    //    T => Turn it off
  741.                 buff[1] = '"';
  742.             
  743.             buff[2] = ESCAPE;
  744.             if ( (theFace & underline) != 0 )    //    T => Turn underline facing on
  745.                 buff[3] = 'X';
  746.             else                                            //    T => Turn it off
  747.                 buff[3] = 'Y';
  748.                 
  749.             cmndBuffSz = 4;
  750.             
  751.             // Next determine if we need to change the size of the font being used
  752.             
  753.             textSize = GXGetShapeTextSize(theShape);
  754.             if (textSize != oldTextSize)    //    T => Must issue LQ command to change font size
  755.             {
  756.                 buff[4] = ESCAPE;                //    The first escape command selects black color
  757.                 buff[5] = kSetColorCommand;
  758.                 buff[6] = '0';
  759.                 
  760.                 buff[7] = ESCAPE;                //    The second escape command selects a draft font
  761.                 buff[8] = 'a';
  762.                 buff[9] = '1';
  763.                 
  764.                 buff[10] = ESCAPE;                //    The third escape command selects the character pitch
  765.                 
  766.                 if ( textSize <= ff(10) )    //    T => Select 10 cpi
  767.                 {
  768.                     buff[11] = 'N';
  769.                 }
  770.                 else    //    T => All other sizes get mapped to 12 cpi
  771.                 {
  772.                     buff[11] = 'E';
  773.                 }
  774.                 
  775.                 // Remember the last text size
  776.                 oldTextSize = textSize;    
  777.                 
  778.                 // Adjust the size of the data to be sent to the printer
  779.                 cmndBuffSz += 8;
  780.             }
  781.             // else - no change in font size
  782.             
  783.             // Send the commands to the printer
  784.             anErr = Send_GXBufferData(buff, cmndBuffSz, gxDontSplitBuffer);
  785.             require(anErr == noErr, CantSendFontCmnd);
  786.  
  787.             // Get the ASCII text and the starting position of the data
  788.             anErr = GetTextAndPosition(theShape, &theChars, &numChars, &textPosition);
  789.             require(anErr == noErr, CantGetTextAndPos);
  790.             
  791.             if ( (currYPos != ff(0)) && (currYPos != textPosition.y) )    //    T => Moving to a lower line, finish the last ;line with a CR
  792.             {
  793.                 char        c = 0x0D;
  794.                 
  795.                 anErr = Send_GXBufferData(&c, 1, gxNoBufferOptions);
  796.                 require(anErr == noErr, CantSendCRCmnd);
  797.             }
  798.             
  799.             // Position the print head to the proper location on the page
  800.             {
  801.                 gxMapping                theMapping;
  802.                 short                    lineFeedSize;
  803.                 Str255                    positionCmndsBuff;
  804.                 unsigned long            bytesInBuff = 0;
  805.                 char                    *p;
  806.  
  807.                 GXGetShapeMapping(theShape, &theMapping);
  808.                 MapPoints(&theMapping, (long) 1, &textPosition);    //    Just map the first point
  809.                 
  810.                 // Now position the print head vertically
  811.  
  812.                 lineFeedSize = (textPosition.y - currYPos) >> 16;
  813.                 anErr = Send_GXRasterLineFeed(&lineFeedSize, positionCmndsBuff, &bytesInBuff, imageData);
  814.                 require(anErr == noErr, CantEmitLineFeeds);
  815.                 
  816.                 // Update the current Y position pointer on the page
  817.                 currYPos = textPosition.y;
  818.  
  819.                 // Now position the print head horizontally on the page
  820.  
  821.                 p = &positionCmndsBuff[bytesInBuff];        
  822.                 *p++ = ESCAPE;
  823.                 *p++ = 'F';
  824.                 Long2Dec((*hGlobals)->leftMargin + FixedToInt(textPosition.x), p);    // Convert left margin into ASCII and place it at the start of the scan line
  825.                 
  826.                 // Update the number of bytes in the buffer
  827.                 bytesInBuff += 6;
  828.  
  829.                 // Send the positioning info to the printer
  830.                 anErr = Send_GXBufferData(positionCmndsBuff, bytesInBuff, gxDontSplitBuffer);
  831.                 require(anErr == noErr, CantSendPositionCmnds);
  832.             }
  833.             
  834.             // Now we send the text data to the printer
  835.             anErr = WriteDraftChars((long **) (*hGlobals)->draftTable, theChars, numChars);
  836.             require(anErr == noErr, CantWriteChars);
  837.         }
  838.     }    // for
  839.  
  840.     // Send one last CR to wrap the last line (if there was one)
  841.     {
  842.         char        c = 0x0D;
  843.         
  844.         anErr = Send_GXBufferData(&c, 1, gxNoBufferOptions);
  845.     }
  846.  
  847.  
  848. /******* Clean-up *******/
  849.  
  850. CantWriteChars:
  851. CantSendPositionCmnds:
  852. CantEmitLineFeeds:
  853. CantSendCRCmnd:
  854. CantGetTextAndPos:
  855. CantSendFontCmnd:
  856.     if (theChars != nil)
  857.         DisposPtr(theChars);
  858.                 
  859.     return(anErr);
  860.     
  861. } // PrintPageInDraftMode 
  862.  
  863. //<FF>
  864. /* ------------------------------------------------------------------------------------    */
  865. /*    SPECIFIC DRIVER UNIVERSAL OVERRIDES                                                    */
  866. /* ------------------------------------------------------------------------------------    */
  867. OSErr SD_Initialize (void) 
  868. /*
  869.     The SD_Initalize message is called when a new job is created.  The standard
  870.     thing to do is to allocate and fill out your globals as you see fit.
  871. */
  872. {
  873.  
  874.     SpecGlobalsHdl     hGlobals;
  875.     OSErr             anErr;
  876.         
  877.     // we make our globals
  878.     hGlobals = (SpecGlobalsHdl) NewHandleClear( sizeof(SpecGlobals) );
  879.     anErr = MemError();
  880.  
  881.     // and we save them away
  882.     SetMessageHandlerInstanceContext(hGlobals);
  883.  
  884.     // is everything okay?
  885.     nrequire(anErr, MNewHandleClear);
  886.     
  887.     // Don't need to initialize because of the NewHandleCLEAR
  888.     //(**hGlobals).draftTable = nil;
  889.     //(**hGlobals).lineFeeds = 0;
  890.     //(**hGlobals).packagingOptions = kNoPackagingOptions;
  891.     //(**hGlobals).idleError         = noErr;
  892.     //(**hGlobals).idleQuery         = false;
  893.     //(**hGlobals).idleTimeout         = 0;
  894.     //(**hGlobals).timeoutPending     = false;
  895.     
  896.     
  897.     return(noErr);
  898.     
  899.     
  900. /*-----EXCEPTION HANDLING------*/
  901.  
  902.  
  903. MNewHandleClear:
  904.     return(anErr);
  905.     
  906. } // SD_Initialize
  907.  
  908.  
  909. //<FF>
  910. /* ------------------------------------------------------------------------------------    */
  911. OSErr SD_ShutDown(void) 
  912. /*
  913.     Shutdown is called when the job is done with.  A good thing to do is to get
  914.     rid of any additional storage that is laying around.
  915. */
  916. {
  917.     // clean up our stuff
  918.     SpecGlobalsHdl hGlobals = GetMessageHandlerInstanceContext();
  919.  
  920.     // get rid of the draft table (if we have one)
  921.     if (hGlobals)
  922.         DisposHandle((**hGlobals).draftTable);
  923.     
  924.     // we get rid of our storage
  925.     DisposHandle((Handle) hGlobals);
  926.     
  927.     // clear out our globals - to avoid double disposes
  928.     SetMessageHandlerInstanceContext(nil);
  929.  
  930.     return(noErr);
  931.     
  932.     
  933. } // SD_ShutDown
  934.  
  935. //<FF>
  936. /* ------------------------------------------------------------------------------------    */
  937. OSErr    SD_DefaultPrinter(gxPrinter thePrinter)
  938. /*
  939.     This call is made to setup the default printer object.  The job of the
  940.     specific driver is to add in any viewDevices that it wishes applications
  941.     to be able to format specifically for.
  942. */
  943. {
  944.     OSErr            anErr;
  945.     gxViewDevice    vd;
  946.     gxJob            theJob = GXGetJob();
  947.     
  948.     // add the standard viewDevices first
  949.     anErr = Forward_GXDefaultPrinter(thePrinter);
  950.     nrequire(anErr, DefaultPrinter);
  951.     
  952.     // add a 144 b/w viewDevice
  953.     vd = NewDeviceResolutionViewDevice();
  954.     {
  955.     gxSetColor        theColors[2];
  956.     gxSetColor        *pColor;
  957.     gxColorSet        theSet;
  958.     
  959.     pColor = &theColors[0];
  960.     
  961.     pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0xFFFF;
  962.     
  963.     pColor++;
  964.     pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0x0000;
  965.     
  966.     theSet = GXNewColorSet(gxRGBSpace, 2, theColors);
  967.     SetViewDeviceColorSet(vd, theSet);
  968.     GXDisposeColorSet(theSet);
  969.     }
  970.         
  971.     anErr = GXAddPrinterViewDevice(thePrinter, vd);
  972.     nrequire(anErr, FailedAddBWViewDevice);
  973.  
  974.     
  975.     // add a 144 color viewDevice with 8 colors in it
  976.     //
  977.     //    Color        Index        R            G            B
  978.     //    white        0            0xFFFF        0xFFFF        0xFFFF        
  979.     //    yellow        1            0xFFFF        0xFFFF        0x0000
  980.     //    magenta        2            0xFFFF        0x0000        0xFFFF
  981.     //    red            3            0xFFFF        0x0000        0x0000
  982.     //    cyan        4            0x0000        0xFFFF        0xFFFF
  983.     //    green        5            0x0000        0xFFFF        0x0000
  984.     //    blue        6            0x0000        0x0000        0xFFFF
  985.     //    black        7            0x0000        0x0000        0x0000
  986.     
  987.     if (PrinterHasColorRibbon(thePrinter))
  988.         {
  989.         gxSetColor        theColors[8];
  990.         gxSetColor        *pColor;
  991.         gxColorSet        theSet;
  992.         short            idx;
  993.  
  994.         vd = NewDeviceResolutionViewDevice();
  995.         
  996.         pColor = &theColors[0];
  997.         for (idx = 0; idx < 8; ++idx)
  998.             {
  999.             // default the color to black
  1000.             pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0x0000;
  1001.             
  1002.             // and give it componants to go along with this index
  1003.             if (idx & 0x04)
  1004.                 pColor->rgb.red     = 0xFFFF;
  1005.             if (idx & 0x02)
  1006.                 pColor->rgb.green     = 0xFFFF;
  1007.             if (idx & 0x01)
  1008.                 pColor->rgb.blue     = 0xFFFF;
  1009.                 
  1010.             // move on to the next color
  1011.             ++pColor;
  1012.             }
  1013.         
  1014.         theSet = GXNewColorSet(gxRGBSpace, 8, theColors);
  1015.         SetViewDeviceColorSet(vd, theSet);
  1016.         GXDisposeColorSet(theSet);
  1017.  
  1018.         anErr = GXAddPrinterViewDevice(thePrinter, vd);
  1019.         nrequire(anErr, FailedAddColorViewDevice);
  1020.         }
  1021.     
  1022.     /* Only if we are the output printer (not the formatting printer) */
  1023.     if (GXGetJobPrinter(theJob) == GXGetJobOutputPrinter(theJob)) {
  1024.         Collection            jobCollection = GXGetJobCollection(GXGetJob());
  1025.         Handle                 jobQualitySettingsHdl;    
  1026.         gxQualityInfo        *qualitySettings;
  1027.         Ptr                    p;
  1028.         Str255                bestString, roughString;
  1029.  
  1030.         // read in our quality mode strings
  1031.         {
  1032.         short    curResFile = CurResFile();
  1033.         
  1034.         UseResFile(GXGetMessageHandlerResFile());
  1035.         
  1036.         GetIndString( bestString, kNewQualityID, kBestString);
  1037.         GetIndString( roughString, kNewQualityID, kRoughString);
  1038.         UseResFile(curResFile);
  1039.         }
  1040.         
  1041.         jobQualitySettingsHdl = NewHandle(0);
  1042.         anErr = MemError();
  1043.         nrequire(anErr, FailedNewHandle);
  1044.  
  1045.         anErr = GetCollectionItemHdl (     jobCollection,
  1046.                                         gxQualityTag,
  1047.                                         gxPrintingTagID,
  1048.                                         jobQualitySettingsHdl );
  1049.  
  1050.         if (anErr == noErr) 
  1051.             {    /* Check for proper structure -- count as not found if different */
  1052.             HLockHi(jobQualitySettingsHdl);
  1053.  
  1054.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1055.             p = qualitySettings->qualityNames;
  1056.  
  1057.             if (qualitySettings->disableQuality) 
  1058.                 anErr = collectionItemNotFoundErr;
  1059.             else if (qualitySettings->qualityCount != 2)
  1060.                 anErr = collectionItemNotFoundErr;
  1061.             else if (! IUEqualString(p, bestString))
  1062.                 anErr = collectionItemNotFoundErr;
  1063.             else if (! IUEqualString(p + p[0] + 1, roughString))
  1064.                 anErr = collectionItemNotFoundErr;
  1065.  
  1066.             HUnlock(jobQualitySettingsHdl);
  1067.             }
  1068.  
  1069.         if (anErr == collectionItemNotFoundErr) 
  1070.             {
  1071.             Size            count;
  1072.  
  1073.             /* Create the proper quality item */
  1074.             SetHandleSize(jobQualitySettingsHdl,(sizeof(gxQualityInfo) + bestString[0] + roughString[0] + 2 ));
  1075.             anErr = MemError();
  1076.             nrequire( anErr, FailedSetHandleSize );
  1077.                 
  1078.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1079.             
  1080.             qualitySettings->disableQuality = false;
  1081.             qualitySettings->defaultQuality = 1;
  1082.             qualitySettings->currentQuality = 1;
  1083.             qualitySettings->qualityCount = 2;
  1084.  
  1085.             count = bestString[0]+1;
  1086.             p = qualitySettings->qualityNames;
  1087.             BlockMove( bestString, p, count );
  1088.  
  1089.             p += count;
  1090.             BlockMove( roughString, p, roughString[0]+1 );
  1091.  
  1092.             /* Add the proper quality item */
  1093.             anErr = AddCollectionItemHdl (     jobCollection,
  1094.                                             gxQualityTag,
  1095.                                             gxPrintingTagID,
  1096.                                             jobQualitySettingsHdl );
  1097.  
  1098.             /* Make it vilatile by driver */
  1099.             if (anErr == noErr)
  1100.                 (void) SetCollectionItemInfo(jobCollection, gxQualityTag, gxPrintingTagID, 0x0000FFFF, gxVolatileOutputDriverCategory);
  1101.  
  1102.             }
  1103.         
  1104. FailedSetHandleSize:
  1105.         DisposHandle(jobQualitySettingsHdl);
  1106.     }
  1107. FailedNewHandle:
  1108.     
  1109.     ncheck(noErr);
  1110.     return(noErr);
  1111.     
  1112.     
  1113.     
  1114. // EXCEPTION HANDLING
  1115. FailedAddColorViewDevice:
  1116. FailedAddBWViewDevice:
  1117.     GXDisposeViewDevice(vd);
  1118.     
  1119. DefaultPrinter:
  1120.     return(anErr);
  1121.     
  1122. } // SD_DefaultPrinter
  1123.  
  1124. //<FF>
  1125. /* ------------------------------------------------------------------------------------    */
  1126.  
  1127. OSErr SD_DefaultFormat(gxFormat theFormat)
  1128. {
  1129.     OSErr                anErr;
  1130.     Handle                 jobQualitySettingsHdl;    
  1131.     
  1132.     anErr = Forward_GXDefaultFormat(theFormat);
  1133.     
  1134.     // now, if the application has set up a special formatting mode, we need to update
  1135.     // the quality mode collection item (and any private ones we use)
  1136.     if (anErr == noErr)
  1137.         {
  1138.         gxPoint                dpiPoint = {ff(72), ff(72)};
  1139.         gxMapping            vdMapping;
  1140.         gxViewDevice        selectedDevice = GXGetPrinterViewDevice(GXGetJobPrinter(GXGetFormatJob(theFormat)), 0);
  1141.         
  1142.         if (selectedDevice != GXGetPrinterViewDevice(GXGetJobPrinter(GXGetFormatJob(theFormat)), 1) )
  1143.             {
  1144.             GXGetViewDeviceMapping(selectedDevice, &vdMapping);
  1145.             MapPoints(&vdMapping, 1, &dpiPoint);
  1146.             
  1147.             {
  1148.             Collection            jobCollection = GXGetJobCollection(GXGetJob());
  1149.             gxQualityInfo        *qualitySettings;
  1150.     
  1151.             jobQualitySettingsHdl = NewHandle(0);
  1152.             anErr = MemError();
  1153.             nrequire(anErr, FailedNewHandle);
  1154.  
  1155.             anErr = GetCollectionItemHdl (     jobCollection,
  1156.                                                 gxQualityTag,
  1157.                                                  gxPrintingTagID,
  1158.                                                jobQualitySettingsHdl );
  1159.  
  1160.             nrequire(anErr, FailedGetCollectionItemHdl);
  1161.  
  1162.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1163.  
  1164.             qualitySettings->currentQuality = 
  1165.                 (dpiPoint.y > ff(100)) ? (qualitySettings->qualityCount-1) : 0;
  1166.  
  1167.             anErr = AddCollectionItemHdl (     jobCollection,
  1168.                                             gxQualityTag,
  1169.                                             gxPrintingTagID,
  1170.                                             jobQualitySettingsHdl );
  1171.                                                  
  1172.             DisposHandle(jobQualitySettingsHdl);
  1173.             }
  1174.  
  1175.         
  1176.             if (anErr == noErr)
  1177.                 {
  1178.                 long    formatOptions;
  1179.                 
  1180.                 // turn off super-res
  1181.                 formatOptions = 0;
  1182.                 anErr = AddCollectionItem(GXGetFormatCollection(theFormat), 
  1183.                     DriverCreator, 0,
  1184.                     sizeof(formatOptions),
  1185.                     &formatOptions);
  1186.                 }
  1187.             }
  1188.         }
  1189.  
  1190. FailedNewHandle:        
  1191.     ncheck(anErr);
  1192.     return(anErr);
  1193.  
  1194. FailedGetCollectionItemHdl:
  1195.     DisposHandle(jobQualitySettingsHdl);
  1196.     return(anErr);
  1197.     
  1198. } // SD_DefaultFormat
  1199.  
  1200. //<FF>
  1201. /* ------------------------------------------------------------------------------------    */
  1202. OSErr SD_DefaultJob()
  1203. /*
  1204.     We override this message to add our default - highest res possible
  1205. */
  1206. {
  1207.     OSErr    anErr;
  1208.     
  1209.     anErr = Forward_GXDefaultJob();
  1210.     if (anErr == noErr)
  1211.         {
  1212.         long        imagewriterOptions = kSuperRes;
  1213.         
  1214.         anErr = AddCollectionItem(GXGetJobCollection(GXGetJob()), 
  1215.                     DriverCreator,
  1216.                     0,
  1217.                     sizeof(imagewriterOptions),
  1218.                     &imagewriterOptions);
  1219.                     
  1220.         }
  1221.  
  1222.  
  1223.     return(anErr);
  1224.     
  1225. } // SD_DefaultJob
  1226.  
  1227. /* ------------------------------------------------------------------------------------    */
  1228. OSErr SD_OpenConnection(void)
  1229. /*
  1230.     The OpenConnection message is sent in order to open the connection to the device.
  1231. */
  1232. {
  1233.     OSErr    anErr;
  1234.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1235.     
  1236.     // how to process idle events
  1237.     (**hGlobals).idleError         = noErr;
  1238.     (**hGlobals).idleQuery         = false;
  1239.     (**hGlobals).idleTimeout     = 0;
  1240.     (**hGlobals).timeoutPending = false;
  1241.     
  1242.     // first, open the connection the standard way
  1243.     anErr = Forward_GXOpenConnection();
  1244.     nrequire(anErr, OpenConnection);
  1245.     
  1246.     // then, bring the configuration file up to date
  1247.     anErr = UpdateConfiguration();
  1248.     nrequire(anErr, UpdateConfiguration);
  1249.     
  1250.     return(noErr);
  1251.     
  1252. // EXCEPTION HANDLING
  1253. UpdateConfiguration:
  1254.     GXCleanupOpenConnection();
  1255.     
  1256. OpenConnection:
  1257.  
  1258.     return(anErr);
  1259.     
  1260. } // SD_OpenConnection
  1261.  
  1262. /* ------------------------------------------------------------------------------------    */
  1263. OSErr SD_CloseConnection(void)
  1264. {
  1265.     unsigned short    statusReturn;
  1266.     OSErr            anErr, anErr2;
  1267.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1268.     ResType            commType = (**hGlobals).commType;
  1269.  
  1270.     if (commType == 'PPTL')
  1271.         {
  1272.         // flush out all data so that we can query the printer properly    one last time
  1273.         anErr = Send_GXWriteData(nil, 0);
  1274.         nrequire(anErr, Send_GXWriteData1);
  1275.         
  1276.         // for PAP: bring the configuration file up to date & check that the printer is online
  1277.         anErr2 = UpdateConfiguration();
  1278.         if (anErr == noErr) anErr = anErr2;
  1279.         }
  1280.     else
  1281.         {
  1282.         // for serial: flush out all data so that we can query the printer properly    one last time
  1283.         anErr = Send_GXWriteData(nil, 0);
  1284.         nrequire(anErr, Send_GXWriteData2);
  1285.  
  1286.         // one last time check up on printer status 
  1287.         if ((**hGlobals).isImageWriterII)
  1288.             {
  1289.             anErr2 = FetchStatusString(&statusReturn, false, true);
  1290.             if (anErr == noErr) anErr = anErr2;
  1291.             }
  1292.         }
  1293.     
  1294. Send_GXWriteData2:
  1295. Send_GXWriteData1:
  1296. FetchStatusString:
  1297.     // close the connection the standard way
  1298.     anErr2 = Forward_GXCloseConnection();
  1299.     if (anErr == noErr) anErr = anErr2;
  1300.         
  1301.     return(anErr);
  1302.     
  1303. } // SD_CloseConnection
  1304.  
  1305. /* ------------------------------------------------------------------------------------    */
  1306. OSErr SD_JobIdle()
  1307. {
  1308.     OSErr            anErr = noErr;
  1309.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1310.     SpecGlobalsPtr    pGlobals;
  1311.     
  1312.     pGlobals = *hGlobals;
  1313.     if ( (pGlobals->idleQuery) && (pGlobals->commType == 'PPTL') )
  1314.         {
  1315.         unsigned short    statusReturn;
  1316.  
  1317.         pGlobals->idleQuery = false;
  1318.         
  1319.         anErr = FetchStatusString(&statusReturn, true, true);
  1320.         nrequire(anErr, FetchStatusString);
  1321.  
  1322.         anErr = Forward_GXJobIdle();
  1323.  
  1324.         // EXCEPTION HANDLING
  1325.         FetchStatusString:
  1326.             pGlobals = *hGlobals;
  1327.             pGlobals->idleQuery = true;
  1328.         }
  1329.     else    
  1330.         anErr = Forward_GXJobIdle();
  1331.     
  1332.     // if we continue looping here too long during the initial query -- give the user
  1333.     // a chance to bail or correct the problem
  1334.     pGlobals = *hGlobals;
  1335.     if ( (!(pGlobals->timeoutPending)) && (pGlobals->idleTimeout != 0) )
  1336.         {
  1337.         if (TickCount() > pGlobals->idleTimeout)
  1338.             {
  1339.             gxStatusRecord        theStat;
  1340.             gxStatusRecord        *pStat = &theStat;
  1341.             
  1342.             pStat->statusOwner    = 'drvr';
  1343.             pStat->statResId     = kDriverStatus;        
  1344.             pStat->statResIndex = kCheckOnline;            
  1345.             pStat->bufferLen      = 0;
  1346.             pStat->dialogResult = nil;
  1347.                         
  1348.             // tell the user to check the printer
  1349.             pGlobals->timeoutPending = true;
  1350.             (void) GXAlertTheUser(pStat);
  1351.             pGlobals = *hGlobals;
  1352.             pGlobals->timeoutPending = false;
  1353.                 
  1354.             // based on the user's response cancel
  1355.             switch (pStat->dialogResult)
  1356.                 {
  1357.                 case ok:
  1358.                     pGlobals->idleTimeout = TickCount() + kQueryTimeout;
  1359.                     break;
  1360.                     
  1361.                 case cancel:
  1362.                     pGlobals->idleError = gxPrUserAbortErr;
  1363.                     break;
  1364.                     
  1365.                 case 3:
  1366.                     pGlobals->idleError = kPutJobOnHoldErr;
  1367.                     break;
  1368.                 }
  1369.  
  1370.             // display "sending data to the printer" message
  1371.             if (anErr == noErr)
  1372.                 anErr = GXReportStatus(kDriverStatus, kSendingData);
  1373.             }
  1374.         }
  1375.         
  1376.     if (anErr == noErr)
  1377.         anErr = pGlobals->idleError;
  1378.         
  1379.     return(anErr);
  1380.     
  1381. } // SD_JobIdle
  1382.  
  1383. /* ------------------------------------------------------------------------------------    */
  1384. OSErr SD_FreeBuffer(gxPrintingBuffer * theBuffer)
  1385. {
  1386.     OSErr            anErr = noErr;
  1387.     OSErr            firstError = noErr;
  1388.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1389.     
  1390.  
  1391.     if ((**hGlobals).commType == 'PPTL')
  1392.         {
  1393.         unsigned short    statusReturn;
  1394.  
  1395.         anErr = FetchStatusString(&statusReturn, true, true);
  1396.         nrequire(anErr, FetchStatusString);
  1397.         }
  1398.         
  1399.     do
  1400.         {
  1401.         // we can idle query now if we need to    
  1402.         (**hGlobals).idleQuery = true;
  1403.  
  1404.         // try to send the buffer again
  1405.         anErr = Forward_GXFreeBuffer(theBuffer);
  1406.         if (firstError == noErr)
  1407.             firstError = anErr;
  1408.     
  1409.         (**hGlobals).idleQuery = false;
  1410.  
  1411.         // timeout dialog!
  1412.         if (anErr == gxAioTimeout)
  1413.             {
  1414.             gxStatusRecord        theStat;
  1415.             gxStatusRecord        *pStat = &theStat;
  1416.             
  1417.             pStat->statusOwner    = 'drvr';
  1418.             pStat->statResId     = kDriverStatus;        
  1419.             pStat->statResIndex = kCheckOnline;            
  1420.             pStat->bufferLen      = 0;
  1421.             pStat->dialogResult = nil;
  1422.                         
  1423.             // tell the user to check the printer
  1424.             (void) GXAlertTheUser(pStat);
  1425.                 
  1426.             // based on the user's response cancel
  1427.             switch (pStat->dialogResult)
  1428.                 {
  1429.                 case ok:
  1430.                     anErr = gxAioTimeout;
  1431.                     break;
  1432.                     
  1433.                 case cancel:
  1434.                     anErr = gxPrUserAbortErr;
  1435.                     break;
  1436.                     
  1437.                 case 3:
  1438.                     anErr = kPutJobOnHoldErr;
  1439.                     break;
  1440.                 }
  1441.             }
  1442.             
  1443.         } while (anErr == gxAioTimeout);
  1444.     
  1445.     // put down the timeout dialog, if we ever put one up
  1446.     if (firstError != noErr)
  1447.         (void) GXReportStatus(kDriverStatus, kSendingData);
  1448.  
  1449.     // error to return from next idle
  1450.     (**hGlobals).idleError = anErr;
  1451.     
  1452. FetchStatusString:        
  1453.     return(anErr);
  1454.     
  1455. } // SD_FreeBuffer
  1456.  
  1457. /* ------------------------------------------------------------------------------------    */
  1458. OSErr SD_DumpBuffer(gxPrintingBuffer * theBuffer)
  1459. {
  1460.     OSErr    anErr;
  1461.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1462.         
  1463.     if ((**hGlobals).commType == 'PPTL')
  1464.         {
  1465.         unsigned short    statusReturn;
  1466.         anErr = FetchStatusString(&statusReturn, true, true);
  1467.         nrequire(anErr, FetchStatusString);
  1468.         }
  1469.     anErr = Forward_GXDumpBuffer(theBuffer);
  1470.  
  1471. FetchStatusString:        
  1472.     return(anErr);
  1473.     
  1474. } // SD_DumpBuffer
  1475.  
  1476. /* ------------------------------------------------------------------------------------    */
  1477. OSErr SD_StartSendPage(gxFormat pageFormat)
  1478. /*
  1479.     The StartSendPage message is sent just before the page begins to be rendered.
  1480.     
  1481.     Note that the StartSendPage message will not be sent until imaging/communication
  1482.     time, so that user interaction alerts are considered okay here
  1483. */
  1484. {
  1485.     OSErr                        anErr = noErr;
  1486.     gxJob                        theJob = GXGetJob();
  1487.     Collection                    jobCollection;
  1488.     gxPaperType                    thePaperType;
  1489.     gxTrayFeedInfo                trayFeedInfo;
  1490.     long                        itemSize = sizeof(trayFeedInfo);
  1491.     ResType                        commType;
  1492.     unsigned short                statusReturn;
  1493.     
  1494.     check(theJob);
  1495.     jobCollection = GXGetJobCollection(theJob);
  1496.     check(jobCollection);
  1497.     
  1498.     // cache communications type
  1499.     commType = (**(SpecGlobalsHdl)GetMessageHandlerInstanceContext()).commType;
  1500.     if (commType == 'PPTL')
  1501.         {
  1502.         anErr = FetchStatusString(&statusReturn, true, true);
  1503.         nrequire(anErr, FetchStatusString);
  1504.         }
  1505.     else
  1506.         statusReturn = 0;
  1507.         
  1508.     // check to see if this particular page is to be manually fed
  1509.     anErr = GetCollectionItem(jobCollection, gxTrayFeedTag, gxPrintingTagID, &itemSize, &trayFeedInfo);
  1510.     nrequire(anErr, FailedGetCollectionItem);
  1511.             
  1512.     // manual feed or out of paper?  Time to ask the user what to do
  1513.     if     (     trayFeedInfo.manualFeedThisPage
  1514.         ||  ( ( (statusReturn & kOutOfPaperMask) != 0 ) )
  1515.         )
  1516.         {
  1517.         // Wait for all IO to complete, so that we can correctly tell the user what to do.
  1518.         // Since the WriteData message makes sure all data is flushed before performing the
  1519.         // IO, this call insures that pending IO is complete.
  1520.         anErr = Send_GXWriteData(nil, 0);
  1521.         nrequire(anErr, FlushAllData);
  1522.  
  1523.  
  1524.         // then, conduct the alert with the user
  1525.         {
  1526.         gxStatusRecord        *pStat;
  1527.         
  1528.         // make a status record containing the request to the user - note that 
  1529.         // we have to make room for ManualFeedRecord OR OutOfPaperRecord, but manual is bigger
  1530.         pStat = (gxStatusRecord *)NewPtrClear(sizeof(gxStatusRecord)  + sizeof(gxManualFeedRecord));
  1531.         anErr = MemError();
  1532.         nrequire(anErr, NewPtrClear);
  1533.                 
  1534.         pStat->statusOwner    = 'univ';
  1535.         pStat->statResId     = gxUnivAlertStatusResourceId;    // we use the built-in status for this
  1536.         pStat->dialogResult = nil;
  1537.         
  1538.         if (trayFeedInfo.manualFeedThisPage)
  1539.             {
  1540.             gxManualFeedRecord    *pFeed;
  1541.             
  1542.             pStat->statResIndex = gxUnivManualFeedIndex;            // status meaning "manual feed alert"
  1543.             pStat->bufferLen      = sizeof(gxManualFeedRecord);
  1544.             pFeed = (gxManualFeedRecord*)&pStat->statusBuffer;
  1545.         
  1546.             // we can switch to autofeed if we want - and tell the user what kind of paper to load in
  1547.             pFeed->canAutoFeed = true;
  1548.             GXGetPaperTypeName(thePaperType = GXGetFormatPaperType(pageFormat), pFeed->paperTypeName);
  1549.             }
  1550.         else
  1551.             {
  1552.             gxOutOfPaperRecord    *pOut;
  1553.             
  1554.             pStat->statResIndex = gxUnivOutOfPaperIndex;            // status meaning "manual feed alert"
  1555.             pStat->bufferLen      = sizeof(gxOutOfPaperRecord);
  1556.             
  1557.             pOut = (gxOutOfPaperRecord*)&pStat->statusBuffer;
  1558.             GXGetPaperTypeName(GXGetFormatPaperType(pageFormat), pOut->paperTypeName);
  1559.             }
  1560.             
  1561.         // keep sending the user the alert until either
  1562.         //  a) the problem resolves itself
  1563.         //  b) the user responds via the dialog
  1564.         //  c) some other (fatal) error happens
  1565.         do
  1566.             {
  1567.             
  1568.             // tell the user
  1569.             anErr = GXAlertTheUser(pStat);
  1570.             
  1571.             // if the paper got suddenly loaded, do an OK
  1572.             if (commType == 'PPTL')
  1573.                 {
  1574.                 (void) FetchStatusString(&statusReturn, true, true);
  1575.                 if ((statusReturn & kOutOfPaperMask) == 0)
  1576.                     {
  1577.                     pStat->dialogResult = ok;
  1578.                     anErr = noErr;
  1579.                     }
  1580.                 }
  1581.                 
  1582.             } while ((anErr == noErr) && (pStat->dialogResult == nil));
  1583.  
  1584.         // based on the user's response, continue, cancel, or switch to auto feed
  1585.         switch ( pStat->dialogResult )
  1586.             {
  1587.             case ok:
  1588.                 // paper is loaded
  1589.                 break;
  1590.                 
  1591.             case cancel:
  1592.                 // user wishes to stop the printing process
  1593.                 anErr = gxPrUserAbortErr;
  1594.                 break;
  1595.                 
  1596.             case gxAutoFeedButtonId:
  1597.                 // do rest of job with auto feed
  1598.                 
  1599.                 {
  1600.                 gxPaperFeedInfo paperFeed;
  1601.                 
  1602.                 /* Update for job */
  1603.                 paperFeed.autoFeed = true;
  1604.                 (void) AddCollectionItem(jobCollection, gxPaperFeedTag, gxPrintingTagID, sizeof(paperFeed), &paperFeed);
  1605.                 }
  1606.                 
  1607.                 /* Update as it may be reused */
  1608.                 trayFeedInfo.manualFeedThisPage = false;    /* Other trayInfo fields are still valid */
  1609.                 (void) AddCollectionItem(jobCollection, gxTrayFeedTag, gxPrintingTagID, sizeof(trayFeedInfo), &trayFeedInfo);
  1610.                 
  1611.                 /* Can pass paper type reference as this IS device communication time */
  1612.                 anErr = Send_GXCheckStatus((Ptr) &thePaperType, sizeof(thePaperType), 0, 'univ');
  1613.                 ncheck(anErr);
  1614.                 
  1615.                 /* No need to reset tray from gxTrayFeedInfo.feedTrayIndex as there is only one tray! */
  1616.                 break;
  1617.                 
  1618.             } // switch
  1619.             
  1620.             
  1621.         // done with the status now
  1622.         DisposPtr((Ptr) pStat);
  1623.         }
  1624.             
  1625.         } // if manual feed job
  1626.         
  1627.     // display "sending data to the printer" message
  1628.     if (anErr == noErr)
  1629.         anErr = GXReportStatus(kDriverStatus, kSendingData);
  1630.         
  1631.     nrequire(anErr, FailedWaitForPaper);
  1632.         
  1633.     // continue with the standard starting of the page
  1634.     anErr = Forward_GXStartSendPage(pageFormat);
  1635.         
  1636.         
  1637. // FALL THROUGH AND HANDLE EXCEPTIONS
  1638.  
  1639. FailedWaitForPaper:
  1640. NewPtrClear:
  1641. FlushAllData:
  1642. FailedGetCollectionItem:
  1643. FetchStatusString:
  1644.     return(anErr);
  1645.     
  1646. } // SD_StartSendPage
  1647.  
  1648. /* ------------------------------------------------------------------------------------    */
  1649. OSErr SD_FinishSendPage()
  1650. {
  1651.     OSErr        anErr = noErr;
  1652.     Str63        formLength;            // should be more than big enough for form skipping
  1653.     char        len = 0;
  1654.  
  1655.     // we may have issued line feeds RIGHT up to the end of the page.  If
  1656.     // we do that and then issue a form feed, we'll kick out a blank page.
  1657.     // to avoid that, we back up a tad and then let the normal form feed
  1658.     // go through.  Option 2 would be to track each and every motion control
  1659.     // we send to the printer -- but that's more work than this.  In addition,
  1660.     // this method makes sure we are synced up exactly to the hardware
  1661.     formLength[len++] = ESCAPE;
  1662.     formLength[len++] = 'T';
  1663.     formLength[len++] = '0';
  1664.     formLength[len++] = '1';
  1665.     formLength[len++] = ESCAPE;
  1666.     formLength[len++] = 'r';
  1667.     formLength[len++] = 0x0A;
  1668.     
  1669.     // reset to forward motion for the form feed
  1670.     formLength[len++] = ESCAPE;
  1671.     formLength[len++] = 'f';
  1672.     
  1673.     anErr = Send_GXBufferData(&formLength[0], len, gxNoBufferOptions );
  1674.     nrequire(anErr, Send_GXBufferData);
  1675.     
  1676.     // Default implementation provides the actual form feed
  1677.     anErr = Forward_GXFinishSendPage();
  1678.     
  1679. // FALL THROUGH EXCEPTION HANDLING
  1680. Send_GXBufferData:
  1681.  
  1682.     return(anErr);
  1683.     
  1684. } // SD_FinishSendPage
  1685.  
  1686. /* ------------------------------------------------------------------------------------    */
  1687. OSErr SD_JobFormatDialog(gxDialogResult*    theResult)
  1688. /*
  1689.     This message is sent in response to the user's request to put up a formatting dialog
  1690. */
  1691. {
  1692.     OSErr                     anErr;
  1693.     gxJobFormatModeTableHdl    theJobFormatModeList;
  1694.     long                    i;
  1695.     gxJob                     theJob = GXGetJob();
  1696.     
  1697.     // set up the JobFormatMode information
  1698.     
  1699.     anErr = GXGetAvailableJobFormatModes(&theJobFormatModeList);
  1700.     if ((!anErr) && (theJobFormatModeList))
  1701.         {
  1702.         for (i = 0; i <= (*theJobFormatModeList)->numModes - 1; ++i) 
  1703.             {
  1704.             if ((*theJobFormatModeList)->modes[i] == gxTextJobFormatMode) 
  1705.                 {
  1706.                 GXSetPreferredJobFormatMode(gxTextJobFormatMode, false);
  1707.                 break;
  1708.                 }
  1709.             }
  1710.         DisposHandle((Handle)theJobFormatModeList);
  1711.         }
  1712.         
  1713.     // do the normal dialogs after handling the job format mode stuff
  1714.     return(Forward_GXJobDefaultFormatDialog(theResult));
  1715.     
  1716. } // SD_JobFormatModeQuery
  1717.  
  1718. /* ------------------------------------------------------------------------------------    */
  1719. OSErr SD_JobFormatModeQuery(    gxQueryType        theQuery,
  1720.                                 void*            srcData,
  1721.                                 void*            dstData)
  1722. /*
  1723.     This message is sent to find out information about the current job format mode.
  1724. */
  1725. {
  1726.     OSErr        anErr = noErr;
  1727.     Handle        theFonts;
  1728.     Handle        theStyles;
  1729.     
  1730.     check(dstData != nil);
  1731.     
  1732.     // What type of query is being requested?
  1733.     switch(theQuery) 
  1734.     {
  1735.         case gxSetStyleJobFormatCommonStyleQuery:
  1736.         {
  1737.             char                *pStyleName;
  1738.  
  1739.             // Fetch the list of supported styles
  1740.             
  1741.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeStylesID, &theStyles);
  1742.             require(anErr == noErr, FailedToLoadStyles1);
  1743.             
  1744.             HNoPurge(theStyles);
  1745.             HLock(theStyles);
  1746.             
  1747.             // Determine which style is being referenced and set the corresponding style (only 2 styles
  1748.             // are currently supported)
  1749.             
  1750.             if (**((short **) theStyles) == 2)    //    T => We have the correct number of styles
  1751.             {
  1752.                 char        whichFace = 0;
  1753.                 
  1754.                 pStyleName = ((char *) *theStyles) + sizeof(short); 
  1755.                 
  1756.                 if ( IUCompString(pStyleName, (char *) srcData) == 0 )    //    T => They want bold face
  1757.                 {
  1758.                     whichFace = bold;
  1759.                 }
  1760.                 else
  1761.                 {
  1762.                     // Point to the next name in the list
  1763.                     pStyleName += *pStyleName + 1;
  1764.  
  1765.                     if ( IUCompString(pStyleName, (char *) srcData) == 0 )    //    T => They want underline face
  1766.                     {
  1767.                         whichFace = underline;
  1768.                     }
  1769.                 }
  1770.  
  1771.                 //    If the client specified a valid face, set it now
  1772.                 if (whichFace != 0)
  1773.                 {
  1774.                     SetStyleCommonFace((gxStyle) dstData, GetStyleCommonFace((gxStyle) dstData) | whichFace);
  1775.                 }
  1776.             }
  1777.             // else - something is wrong with our resource
  1778.             
  1779.             // Dump the temporary handle
  1780.             DisposHandle(theStyles);
  1781.             
  1782.             break;
  1783.         }
  1784.             
  1785.         case gxGetJobFormatFontCommonStylesQuery:
  1786.         {
  1787.             short                numStyles;
  1788.             short                i;
  1789.             char                *pStyleName;
  1790.  
  1791.             // Fetch the list of supported styles
  1792.             
  1793.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeStylesID, &theStyles);
  1794.             require(anErr == noErr, FailedToLoadStyles2);
  1795.             
  1796.             HNoPurge(theStyles);
  1797.             HLock(theStyles);
  1798.             
  1799.             // Determine the number of styles in the list
  1800.             numStyles = **((short **) theStyles);
  1801.  
  1802.             if (*(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on the styles
  1803.                 SetHandleSize(*(Handle *)dstData, sizeof(gxStyleNameTable) + ((numStyles - 1) * sizeof(Str255)));
  1804.             else
  1805.                 *(Handle *)dstData = NewHandle(sizeof(gxStyleNameTable) + ((numStyles - 1) * sizeof(Str255)));
  1806.             
  1807.             anErr = MemError();
  1808.             require(anErr == noErr, StyleTableResizeFailed);
  1809.             
  1810.             // Now extract the name of each of the supported fonts
  1811.             
  1812.             for (i = 1, pStyleName = ((char *) *theStyles) + sizeof(short); i <= numStyles; ++i, pStyleName += *pStyleName + 1)
  1813.             {
  1814.                 BlockMove(pStyleName, (*((gxStyleNameTableHdl) *(Handle *)dstData))->styleNames[i - 1], *pStyleName + 1);
  1815.             }
  1816.             
  1817.             (*((gxStyleNameTableHdl) *(Handle *)dstData))->numStyleNames = numStyles;
  1818.             
  1819.             // Dump the temporary handle
  1820.             DisposHandle(theStyles);
  1821.             
  1822.             break;
  1823.         }
  1824.             
  1825.         case gxGetJobFormatLineConstraintQuery:            //    This type of query is not supported
  1826.             if (*(Handle *)dstData != nil)
  1827.                 SetHandleSize(*(Handle *)dstData, 0);        // Don't return any data
  1828.             break;
  1829.             
  1830.         case gxGetJobFormatFontsQuery:
  1831.         {
  1832.             short                numFonts;
  1833.             short                i;
  1834.             char                *pFontName;
  1835.  
  1836.             // Fetch the list of supported fonts
  1837.             
  1838.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeFontsID, &theFonts);
  1839.             require(anErr == noErr, FailedToLoadFonts);
  1840.             
  1841.             HNoPurge(theFonts);
  1842.             HLock(theFonts);
  1843.             
  1844.             // Determine the number of fonts in the list
  1845.             numFonts = **((short **) theFonts);
  1846.  
  1847.             if (*(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on the fonts
  1848.                 SetHandleSize(*(Handle *)dstData, sizeof(gxFontTable) + ((numFonts - 1) * sizeof(gxFont)));
  1849.             else
  1850.                 *(Handle *)dstData = NewHandle(sizeof(gxFontTable) + ((numFonts - 1) * sizeof(gxFont)));
  1851.             
  1852.             anErr = MemError();
  1853.             require(anErr == noErr, FontTableResizeFailed);
  1854.             
  1855.             // Now generate a reference to each of the supported fonts
  1856.             
  1857.             for (i = 1, pFontName = ((char *) *theFonts) + sizeof(short); i <= numFonts; ++i, pFontName += *pFontName + 1)
  1858.             {
  1859.                 gxFont            thisFont;
  1860.                 gxFontTable        *pFontTable;
  1861.             
  1862.                 thisFont = FindPNameFont(gxFullFontName, pFontName);
  1863.                 
  1864.                 pFontTable = *((gxFontTableHdl) *(Handle *)dstData);
  1865.                 pFontTable->fonts[i - 1] = thisFont;
  1866.             }
  1867.             
  1868.             (*((gxFontTableHdl) *(Handle *)dstData))->numFonts = numFonts;
  1869.             
  1870.             // Dump the temporary handle
  1871.             DisposHandle(theFonts);
  1872.  
  1873.             break;
  1874.         }
  1875.             
  1876.         case gxGetJobFormatFontConstraintQuery:
  1877.         {
  1878.             gxPositionConstraintTable        *pPositionTable;
  1879.             
  1880.             if ( *(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on position constraints
  1881.                 SetHandleSize(*(Handle *)dstData, sizeof(gxPositionConstraintTable) + sizeof(Fixed));
  1882.             else
  1883.                 *(Handle *)dstData = NewHandle( sizeof(gxPositionConstraintTable) + sizeof(Fixed) );
  1884.             
  1885.             pPositionTable = *((gxPositionConstraintTableHdl) *(Handle *)dstData);
  1886.             
  1887.             pPositionTable->phase.x     = 0;                //    Start at the top left corner of the page
  1888.             pPositionTable->phase.y     = 0;
  1889.             pPositionTable->offset.x     = ff(12);        // Indent from the top left by a six lines per inch margin
  1890.             pPositionTable->offset.y     = ff(12);         
  1891.             pPositionTable->numSizes     = 2;                // Two font sizes supported
  1892.             pPositionTable->sizes[0]     = ff(10);         // 10 pitch
  1893.             pPositionTable->sizes[1]     = ff(12);         // 12 pitch
  1894.             
  1895.             break;
  1896.         }
  1897.     } // switch
  1898.     
  1899.     return(anErr);
  1900.     
  1901.  
  1902. /******* Clean-up *******/
  1903.  
  1904. StyleTableResizeFailed:
  1905.     DisposHandle((Handle) theStyles);
  1906.     return(anErr);
  1907.  
  1908. FontTableResizeFailed:
  1909.     DisposHandle((Handle) theFonts);
  1910.  
  1911. FailedToLoadStyles1:
  1912. FailedToLoadStyles2:
  1913. FailedToLoadFonts:
  1914.     return(anErr);
  1915.     
  1916. } // SD_JobFormatModeQuery
  1917.  
  1918. //<FF>
  1919. /* ------------------------------------------------------------------------------------    */
  1920. OSErr SD_SetupImageData(
  1921.     gxRasterImageDataHdl hImageData)        // raster image data stuff
  1922. /*
  1923.     This message is called to setup the constant data used for imaging the entire job.
  1924. */
  1925. {
  1926.  
  1927.     SpecGlobalsHdl                 hGlobals = GetMessageHandlerInstanceContext();
  1928.     OSErr                        anErr;
  1929.     gxRasterImageDataPtr        pImageData;
  1930.     Boolean                     isJobNotFinalQuality, isTextJobFormatMode;
  1931.     long                        imagewriterOptions;
  1932.     
  1933.     // do the default setup
  1934.     anErr = Forward_GXSetupImageData(hImageData);
  1935.     nrequire(anErr, Forward_GXSetupImageData);
  1936.     
  1937.     // test for 'final' quality mode
  1938.     isJobNotFinalQuality = !JobIsBest(&imagewriterOptions);
  1939.     
  1940.     // test for textJobFormatMode
  1941.     isTextJobFormatMode = ( GXGetJobFormatMode( GXGetJob() ) == gxTextJobFormatMode);
  1942.             
  1943.     // if the job is not final quality or using textJobFormatMode, downgrade the imaging data to our lower quality
  1944.     if (isJobNotFinalQuality  ||  isTextJobFormatMode)
  1945.         {
  1946.         // ROUGH OR TEXT MODE
  1947.         
  1948.         // dereference for size and speed    
  1949.         pImageData = *hImageData;
  1950.                 
  1951.         // image at 80 or 72 dpi
  1952.         if (imagewriterOptions & kSuperRes)
  1953.             pImageData->hImageRes = ff(80);
  1954.         else
  1955.             pImageData->hImageRes = ff(72);
  1956.         pImageData->vImageRes = ff(72);
  1957.         
  1958.         // textJobFormatMode loads up the draft table, else setup halftones
  1959.         if (isTextJobFormatMode)
  1960.             {
  1961.             Handle            draftTable;
  1962.  
  1963.             anErr = Send_GXFetchTaggedDriverData('idft', gxPrintingDriverBaseID, &draftTable);
  1964.             nrequire(anErr, FailedToLoadDraftTable);
  1965.             
  1966.             // store away the draft table
  1967.             (**hGlobals).draftTable = draftTable;
  1968.  
  1969.             // Download something?    
  1970.             anErr = Send_GXFetchTaggedDriverData('idft', gxPrintingDriverBaseID+1, &draftTable);
  1971.             if (anErr == resNotFound)
  1972.                 {
  1973.                 draftTable = nil;
  1974.                 anErr = noErr;
  1975.                 }
  1976.             nrequire(anErr, GetDownloadTable);    
  1977.         
  1978.             if (draftTable)
  1979.                 {
  1980.                 HLock(draftTable);
  1981.                 anErr = Send_GXBufferData(*draftTable, GetHandleSize(draftTable), gxDontSplitBuffer);
  1982.                 DisposHandle(draftTable);
  1983.                 nrequire(anErr, SendDownloadTable);
  1984.                 }
  1985.             }
  1986.         else
  1987.             {            
  1988.             // use dither level that will look better at 72 dpi 
  1989.             // resolution than our default values (MAYBE: 4 is the default now anyway)
  1990.             pImageData->theSetup.planeSetup[0].planeHalftone.method = 4;
  1991.             
  1992.             // of course, turn off color matching when in non-final mode!
  1993.             pImageData->theSetup.planeSetup[0].planeProfile = nil;
  1994.             }
  1995.             
  1996.         if (isJobNotFinalQuality)
  1997.             {
  1998.             if (imagewriterOptions & kSuperRes)
  1999.                 {
  2000.                 // use bidirectional instead of unidirectional
  2001.                 // and also <esc>N instead of <esc>p for quality mode
  2002.                 pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+3;
  2003.                 }
  2004.             else
  2005.                 {
  2006.                 // use bidirectional instead of unidirectional
  2007.                 // and also <esc>n instead of <esc>p for quality mode
  2008.                 pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+2;
  2009.                 }
  2010.             }
  2011.         
  2012.         // packaging data
  2013.         pImageData->packagingInfo.headHeight         = 8;        // 8 pins (instead of 16)
  2014.         pImageData->packagingInfo.numberPasses         = 1;        // in 1 head pass (instead of 2)
  2015.         pImageData->packagingInfo.passOffset         = 0;        // with no space between passes
  2016.         }
  2017.     else
  2018.         {
  2019.         // FINAL QUALITY
  2020.         
  2021.         // dereference for size and speed    
  2022.         pImageData = *hImageData;
  2023.                 
  2024.         // image at 160 or 144 dpi
  2025.         if (imagewriterOptions & kSuperRes)
  2026.             {
  2027.             pImageData->hImageRes = ff(160);
  2028.             pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+1;
  2029.             }
  2030.         else
  2031.             {
  2032.             pImageData->hImageRes = ff(144);
  2033.             pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+0;
  2034.             }
  2035.         }
  2036.     
  2037.     // not a color ribbon?  Setup for black and white - do a B/W halftone rather than a dither
  2038.     if (!PrinterHasColorRibbon(GXGetJobOutputPrinter(GXGetJob())))
  2039.         {
  2040.         // dereference for size and speed    
  2041.         pImageData = *hImageData;
  2042.  
  2043.         // one plane, no color flags, move the halftone info up into correct position
  2044.         pImageData->theSetup.planes = 1;
  2045.         pImageData->theSetup.depth = 1;
  2046.         pImageData->packagingInfo.colorPasses = 1;
  2047.         pImageData->packagingInfo.packageOptions = 0;
  2048.         pImageData->theSetup.planeSetup[0].planeSpace = gxNoSpace;
  2049.         pImageData->theSetup.planeSetup[0].planeSet = nil;
  2050.         pImageData->theSetup.planeSetup[0].planeProfile = nil;
  2051.         pImageData->theSetup.planeSetup[0].planeOptions = gxDefaultOffscreen;
  2052.         pImageData->theSetup.planeSetup[0].planeHalftone.method = gxRoundDot;
  2053.         pImageData->theSetup.planeSetup[0].planeHalftone.tintSpace = gxRGBSpace;
  2054.         }
  2055.  
  2056.     return(noErr);
  2057.     
  2058. // EXCEPTION HANDLING
  2059. SendDownloadTable:
  2060. GetDownloadTable:
  2061.     DisposHandle((**hGlobals).draftTable);
  2062.     (**hGlobals).draftTable = nil;
  2063.     
  2064. FailedToLoadDraftTable:
  2065. Forward_GXSetupImageData:
  2066.     return(anErr);
  2067.     
  2068. } // SD_SetupImageData
  2069.  
  2070. /* ------------------------------------------------------------------------------------    */
  2071. OSErr SD_FetchDriverData(
  2072.     ResType            theType,
  2073.     short            theID,
  2074.     Handle*            theData)
  2075. {
  2076.  
  2077.     OSErr    anErr;
  2078.     
  2079.     anErr = Forward_GXFetchTaggedDriverData(theType, theID, theData);
  2080.     
  2081.     // do the translation at the proper DPI by modifying the old API
  2082.     // customization resource
  2083.     if ( (anErr   == noErr)    &&                 // got the resource okay
  2084.          (theType == 'cust')   &&                // it was a customization resource 
  2085.          (theID   == -8192)   )                    // with the old API id
  2086.         {
  2087.         long imagewriterOptions;
  2088.         
  2089.         if (!JobIsBest(&imagewriterOptions))
  2090.             {
  2091.             **((short**)theData)   = 72;
  2092.             **((short**)theData+1) = 72;
  2093.             }
  2094.         }
  2095.         
  2096.     return(anErr);
  2097.     
  2098. } // SD_FetchDriverData
  2099.  
  2100.  
  2101. /* ------------------------------------------------------------------------------------    */
  2102. OSErr SD_RenderPage(    gxFormat                theFormat,
  2103.                         gxShape                    thePage,
  2104.                         gxPageInfoRecord        *pageInfo,
  2105.                         gxRasterImageDataHdl    imageInfo)
  2106. /*
  2107.     The message sent to render an entire page.
  2108. */
  2109. {
  2110.  
  2111.     OSErr    theError = noErr;
  2112.  
  2113.     // if not text mode, do it the normal (raster) way
  2114.     if (GXGetJobFormatMode(GXGetJob()) != gxTextJobFormatMode) 
  2115.         {
  2116.         gxRectangle            paperSize;
  2117.         Str63                formLength;            // should be more than big enough for form skipping
  2118.         char                aNumber[8];
  2119.         char                len = 0;
  2120.         short                formLen;            // form length (in 144 dpi)
  2121.         short                i;
  2122.         
  2123.         
  2124.         // find out how big our paper is
  2125.         GXGetPaperTypeDimensions(GXGetFormatPaperType(theFormat), nil, &paperSize);
  2126.         
  2127.         // determine the left margin (in pixels)
  2128.         {
  2129.         SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  2130.         SpecGlobalsPtr            pGlobals;
  2131.         gxRasterImageDataPtr    pImageData;
  2132.  
  2133.         check(hGlobals);
  2134.  
  2135.         // dereference for size and speed    
  2136.         pImageData     = *imageInfo;
  2137.         pGlobals = *hGlobals;
  2138.         paperSize.left += ff(18);        // ImageWriter's can't go tighter than .25 inch
  2139.         if (paperSize.left > 0)
  2140.             paperSize.left = 0;
  2141.         pGlobals->leftMargin     = FixedToInt(
  2142.                                     FixMul(-paperSize.left, 
  2143.                                         FixDiv(pImageData->hImageRes, ff(72))));
  2144.         
  2145.         // set this to be the top of form
  2146.         formLength[len++] = ESCAPE;
  2147.         formLength[len++] = 'v';
  2148.  
  2149.         // set the form length to be the size of the page iff ImageWriterII
  2150.         if (pGlobals->isImageWriterII)
  2151.             {
  2152.             formLength[len++] = ESCAPE;
  2153.             formLength[len++] = 'H';
  2154.             formLen = FixedToInt(FixMul(paperSize.bottom-paperSize.top, ff(2)) );    // length is set in 144 dpi
  2155.             NumToString(formLen, aNumber);
  2156.             for (i = 0; i < 4-aNumber[0]; ++i)
  2157.                 formLength[len++] = '0';
  2158.             for (i = 1; i <= aNumber[0]; ++i)
  2159.                 formLength[len++] = aNumber[i];
  2160.             }
  2161.         }
  2162.  
  2163.         // NOW: move over the top margin
  2164.         formLen = -FixedToInt( FixMul(paperSize.top, ff(2)) );
  2165.         
  2166.             // Forward line feed
  2167.             formLength[len++] = ESCAPE;
  2168.             formLength[len++] = 'f';
  2169.  
  2170.             // send multiples of 99
  2171.             if (formLen >= 99)
  2172.                 {
  2173.                 formLength[len++] = ESCAPE;
  2174.                 formLength[len++] = 'T';
  2175.                 formLength[len++] = '9';
  2176.                 formLength[len++] = '9';
  2177.                 while (formLen >= 99)
  2178.                     {
  2179.                     formLength[len++] = 0x0A;        // line feed
  2180.                     
  2181.                     formLen -= 99;
  2182.                     }
  2183.                 }
  2184.                 
  2185.             // send remaining line feeds
  2186.             if (formLen > 0)
  2187.                 {
  2188.                 formLength[len++] = ESCAPE;
  2189.                 formLength[len++] = 'T';
  2190.                 NumToString(formLen, aNumber);
  2191.                 if (aNumber[0] == 1)
  2192.                     {
  2193.                     formLength[len++] = '0';
  2194.                     formLength[len++] = aNumber[1];
  2195.                     }
  2196.                 else
  2197.                     {
  2198.                     formLength[len++] = aNumber[1];
  2199.                     formLength[len++] = aNumber[2];
  2200.                     }
  2201.                 formLength[len++] = 0x0A;        // line feed
  2202.                 }
  2203.  
  2204.  
  2205.         // we've got all of this data, now send it
  2206.         theError = Send_GXBufferData(&formLength[0], len, gxNoBufferOptions );
  2207.         nrequire(theError, SetFormLength);        
  2208.                 
  2209.         // continue with normal rendering
  2210.         theError = Forward_GXRenderPage(theFormat, thePage, pageInfo, imageInfo);
  2211.         } 
  2212.     else 
  2213.         {
  2214.         theError = PrintPageInDraftMode(thePage, imageInfo);
  2215.         }
  2216.  
  2217. failed_WrongShape:
  2218. SetFormLength:
  2219.     return(theError);
  2220.     
  2221. } // SD_RenderPage
  2222.  
  2223.  
  2224. //<FF>
  2225. /* ------------------------------------------------------------------------------------    */
  2226. /*    SPECIFIC DRIVER RASTER OVERRIDES                                                    */
  2227. /* ------------------------------------------------------------------------------------    */
  2228. OSErr SD_LineFeed (
  2229.     short *lineFeedSize,                         // amount to line feed by
  2230.     Ptr buffer, unsigned long    * bufferPos,     // data goes here
  2231.     gxRasterImageDataHdl hImageData)            // raster image data stuff
  2232. /*
  2233.     Message is sent to output paper advance commands to the printer
  2234. */
  2235. {
  2236.  
  2237.     OSErr    anErr;
  2238.     Boolean    amLowRes;
  2239.     short    actualLineFeed = *lineFeedSize;
  2240.     
  2241.     amLowRes = ((**hImageData).vImageRes == ff(72));
  2242.     // if we are in low res mode, we double the line feed size, as all ImageWriter 
  2243.     // line feed commands are expressed at 144 dpi.
  2244.     if (amLowRes)
  2245.         *lineFeedSize <<= 1;
  2246.     
  2247.     // optimize small motions (particularlly -1 followed by +1 with no data between)
  2248.     // into groups.  This gets rid of the "paper dance" for blank colors passes.
  2249.     {    
  2250.     SpecGlobalsHdl    hGlobals = GetMessageHandlerInstanceContext();
  2251.     SpecGlobalsPtr    pGlobals = *hGlobals;
  2252.     
  2253.     if (    (pGlobals->packagingOptions == kDoSmallLineFeeds) || 
  2254.             (*lineFeedSize < -1) || 
  2255.             (*lineFeedSize > 1) )
  2256.         {
  2257.         *lineFeedSize += pGlobals->lineFeeds;
  2258.         pGlobals->lineFeeds = 0;
  2259.         // do the line feed in the default way
  2260.         anErr = Forward_GXRasterLineFeed(lineFeedSize, buffer, bufferPos, hImageData);
  2261.         }
  2262.     else
  2263.         {
  2264.         pGlobals->lineFeeds += *lineFeedSize;
  2265.         *lineFeedSize = 0;
  2266.         anErr = noErr;
  2267.         }
  2268.     }
  2269.     
  2270.     // and if in low quality mode, we divide the result to make up for the multiplication
  2271.     // that we do above
  2272.     if (amLowRes)
  2273.         *lineFeedSize >>= 1;    
  2274.             
  2275.     return(anErr);
  2276.     
  2277. } // SD_LineFeed
  2278.  
  2279. //<FF>
  2280. /* ------------------------------------------------------------------------------------    */
  2281. OSErr SD_PackageBitmap (
  2282.     gxRasterPackageBitmapRec    *pPackage,
  2283.     Ptr                         buffer,     // data goes here + bufferPos
  2284.     unsigned long                 *bufferPos,    // how much of the buffer already is full
  2285.     gxRasterImageDataHdl         hImageData)    // private image data
  2286. /*
  2287.     Packages a bitmap for the ImageWriter
  2288.     This routine is called in order to add your rotated and packaged pixel
  2289.     data to the buffer.  It is called once for each head pass.  This routine
  2290.     is pretty complex because it also does IW run length compression.  
  2291.     
  2292.     It must do the following:
  2293.         
  2294.     1)    Start filling the buffer from buffer+bufferPos.  Remember
  2295.         that this pointer may not be word aligned - so be careful
  2296.         assigning things into it.
  2297.         
  2298.     2)    If your printer does SetMargins, put a "fake" set of commands at
  2299.         the begining of the data.  Since most of the time you don't
  2300.         know the margins, you can save away the value of the bufferPos,
  2301.         and backpatch it after you have finished with the offscreen.
  2302.         SetMargins is used on printers that allow you to not send starting
  2303.         and ending whitespace.
  2304.         
  2305.     3)    Add in the rotated data for your printer.  The data to stuff starts
  2306.         at location startY in hOffscreen.  Stuff the bits from here until
  2307.         you reach startY+<your band size>, which is the size of your single
  2308.         band in this resolution mode.  Increment your number by 
  2309.         <your pass offset> + 1, which is the number of microspaces
  2310.         you will send between head passes to form this band.   Take care
  2311.         that you don't step off of the end of the offscreen in this operation,
  2312.         you may be called with startY at the end of the offscreen if the first part
  2313.         of the band is white.
  2314.         
  2315.         colorBand contains the color band which you should be stuffing, from
  2316.         1 to the number of color passes your printer needs (usually 4).
  2317.         Pack in the correct color band.  The packager will call you once
  2318.         for each color band, and correctly handle line feeds and backward
  2319.         line feeds to do the correct thing.  If your printer takes full
  2320.         RGB or CYMK data, I would define your number of colors to be
  2321.         1 and pack the full RGB or CYMK data with the one call to StuffBuffers.
  2322.         
  2323.         If you request kSendAllColors in your raster pack resource, then this
  2324.         message will always be called for all color passes, even those that
  2325.         do not have data on them.  For some printers, this is useful.  For the
  2326.         case of the ImageWriter, this option is not specified, so this message
  2327.         will only be sent for colors that actually have dirty bits within them.
  2328.         
  2329.     4)    Backpatch SetMargins from your saved value in step 2) now that you
  2330.         know the margins.
  2331.         
  2332.     5)    Increment bufferPos by the number of bytes you have
  2333.         added to the buffer.  Be sure to take into account the Set Margins
  2334.         command if you added one.
  2335.  
  2336.     
  2337. */
  2338. {
  2339. #pragma unused (isColorDirty)
  2340.  
  2341.     OSErr                    anErr;                    // would you beleive we could make mistakes?
  2342.     ScanLinePtr                pTheScanLine;            // Pointer to the start of scan line data
  2343.     unsigned short            lastDirtyCol;            // Last dirty part of the scan line
  2344.     unsigned short            firstDirty;                // First dirty pixel
  2345.     unsigned short            lastDirty;                // Last dirty pixel
  2346.     Boolean                    bandIsDirty;            // Is this band dirty?
  2347.     unsigned short            numberBytesAdded;        // Number of bytes we have added to the row
  2348.     unsigned short            repeatCount;            // Number of times we have seen this bitmap
  2349.     
  2350.     register unsigned short    whichCol;                // Index into the scan line data
  2351.     register unsigned short    x,y;                    // Index values into the offscreen
  2352.         
  2353.     register Ptr            thePtr;                    // Pointer to each Y scanline
  2354.     register unsigned char    tempColumn;                // Placeholder for the working column
  2355.     unsigned char            lastColumn;                // What was in the contents of the last column?
  2356.     
  2357.     Ptr                        basePtr;                // Pointer to current X byte
  2358.     unsigned char            outputMask;                // Mask of bit to set in rotated image
  2359.     unsigned char            inputMask;                // Mask of bit to look at in X
  2360.     unsigned char            startingInputMask;        // Mask of first bit of interest
  2361.     unsigned short            yPointerOffset;            // Increment pointer by this to get to next scanline
  2362.     
  2363.     unsigned short            endY, endX, incrY;        // To remove loop invariants.
  2364.     unsigned short            packingColor;            // number of colors packing
  2365.     unsigned long             originalBufferPos;        // where we were in the buffer before we started;
  2366.     short                    originalLineFeeds;        // how many line feeds did we have before?
  2367.     SpecGlobalsHdl            hGlobals = GetMessageHandlerInstanceContext();
  2368.     SpecGlobalsPtr            pGlobals = *hGlobals;
  2369.     
  2370. /* This macro stores one group into the pointer:
  2371.     P = Pointer to fill into
  2372.     G = Character for group
  2373.     S = Length of group run in pixels
  2374. */
  2375. #define EMITGROUP(P, G, S)                    \
  2376.         P->cEscape = ESCAPE;                \
  2377.         P->cCommand = G;                    \
  2378.         Long2Dec(S, P->cLineLength);        
  2379.  
  2380.     // save away original position in order to do a restore should the band be clean
  2381.     originalBufferPos = *bufferPos;
  2382.     originalLineFeeds = pGlobals->lineFeeds;
  2383.     if (originalLineFeeds == 0)
  2384.         {
  2385.         anErr = noErr;
  2386.         }
  2387.     else
  2388.         {
  2389.         // if we have any extra line feeds saved up, do them now!    
  2390.         pGlobals->lineFeeds = 0;
  2391.         pGlobals->packagingOptions = kDoSmallLineFeeds;
  2392.         anErr = Send_GXRasterLineFeed(&originalLineFeeds, buffer, bufferPos, hImageData);
  2393.         pGlobals = *hGlobals;
  2394.         pGlobals->packagingOptions = kNoPackagingOptions;
  2395.         }
  2396.     nrequire(anErr, SendInitialLineFeeds);
  2397.     
  2398.     /* Set color iff ImageWriterII */
  2399.     if ((**hGlobals).isImageWriterII)
  2400.         {
  2401.         pTheScanLine = (ScanLinePtr) (buffer + kSetMarginsSize + (*bufferPos));
  2402.         
  2403.         /* Set color mode for this scan line, if needed */
  2404.         pTheScanLine->cColorEscape        = ESCAPE;
  2405.         pTheScanLine->cSetColorCommand    = kSetColorCommand;
  2406.         
  2407.         packingColor = (*hImageData)->packagingInfo.colorPasses;
  2408.         if (packingColor == 4)
  2409.             switch (pPackage->colorBand)
  2410.                 {
  2411.                 case 1: // yellow
  2412.                     pTheScanLine->cColor    = '1';
  2413.                     startingInputMask = 0x10;
  2414.                     break;
  2415.                     
  2416.                 case 2: // magenta
  2417.                     pTheScanLine->cColor    = '2';
  2418.                     startingInputMask = 0x20;
  2419.                     break;
  2420.     
  2421.                 case 3: // cyan
  2422.                     pTheScanLine->cColor    = '3';
  2423.                     startingInputMask = 0x40;
  2424.                     break;
  2425.                     
  2426.                 case 4: // black
  2427.                     pTheScanLine->cColor    = '0';
  2428.                     startingInputMask = 0x80;
  2429.                     break;
  2430.                     
  2431.                 }
  2432.         else
  2433.             {
  2434.             pTheScanLine->cColor = '0';
  2435.             startingInputMask = 0x80;
  2436.             }
  2437.         }
  2438.     else    /* Backup to eliminate cColorEscape, cSetColorCommand and cColor */
  2439.         {
  2440.         pTheScanLine = (ScanLinePtr) (buffer + kSetMarginsSize + (*bufferPos) - 3);
  2441.         packingColor = (*hImageData)->packagingInfo.colorPasses;
  2442.         startingInputMask = 0x80;
  2443.         }
  2444.  
  2445.     /* Start with the first bit in the offscreen */
  2446.     inputMask = startingInputMask;
  2447.         
  2448.     /* We start out with no dirty bits */
  2449.     firstDirty = 0;
  2450.     lastDirty = 0;
  2451.     bandIsDirty = false;
  2452.     
  2453.     /* Set our array index to zero */
  2454.     whichCol = 0;
  2455.     lastDirtyCol = 0;
  2456.     numberBytesAdded = 0;
  2457.     
  2458.     /* Set up RLL variables */
  2459.     repeatCount = 0;
  2460.     lastColumn = 0;
  2461.     
  2462.     /* Get the byte pointer for the start of this color band */
  2463.     basePtr = pPackage->bitmapToPackage->image;
  2464.     
  2465.     /* Get the byte pointer for the start of the first scan line */ 
  2466.     basePtr += pPackage->startRaster * pPackage->bitmapToPackage->rowBytes;
  2467.             
  2468.     /* Save away loop invariants */
  2469.     endY     = pPackage->startRaster + (*hImageData)->packagingInfo.headHeight;        // Ending scan line
  2470.     incrY     = (*hImageData)->packagingInfo.passOffset + 1;            // Number of scanlines to increment by
  2471.     endX     = pPackage->dirtyRect.right;                                // Ending X pos
  2472.     yPointerOffset = incrY * pPackage->bitmapToPackage->rowBytes;            // amount to add to the input
  2473.                                                             // pointer to move to the next scanline
  2474.  
  2475.     /* If the ending position is too large for the bitmap we have been given,
  2476.        truncate it, so that we don't print garbage */
  2477.     if (endY > pPackage->bitmapToPackage->height)
  2478.         endY = pPackage->bitmapToPackage->height;
  2479.     
  2480.     /* For the entire width of the offscreen, move a rolling mask along in the
  2481.        X direction, rotating up 8 bits of Y data per column.  In addition, compress
  2482.        runs of columns that are > 14 length. */
  2483.     for (x = 0; x < endX; x++)
  2484.         {        
  2485.         /* The bits in this column are clear to begin with */
  2486.         tempColumn = 0;
  2487.         
  2488.         /* Which byte to look at in the input buffer */
  2489.         thePtr = basePtr;
  2490.         
  2491.         /*     Where to place the bit in the output. The ImageWriter takes the bit
  2492.             pattern upside down. */
  2493.         outputMask = 0x01;
  2494.         
  2495.         /* Scan through this band, setting each of the 8 bits == the bit in that scan line */
  2496.         for (y = pPackage->startRaster; y < endY; y += incrY)
  2497.             {
  2498.             /* If we have a bit in the input, rotate it into the output */
  2499.             if ((*thePtr) & inputMask)
  2500.                 tempColumn |= outputMask;
  2501.  
  2502.             // move onto next position in the output data                
  2503.             outputMask <<= 1;
  2504.             
  2505.             // move onto the next scan line in the input data
  2506.             thePtr += yPointerOffset;
  2507.             } // for y
  2508.             
  2509.             
  2510.         /* Save the column info */ 
  2511.         pTheScanLine->iTheData[whichCol] = tempColumn;
  2512.         
  2513.         /* Get the next bit from the current pointer */
  2514.         inputMask >>= packingColor;
  2515.         if (!inputMask)
  2516.             {
  2517.             /* If we run out of bits, get the next byte */
  2518.             basePtr++;
  2519.             
  2520.             /* And reset the bit mask to the first bit */
  2521.             inputMask = startingInputMask;
  2522.             }
  2523.             
  2524.         /* If we have some form of data */
  2525.         if (tempColumn != 0)
  2526.             {
  2527.             if (!bandIsDirty)
  2528.                 {
  2529.                 /* This is the first dirty pixels we have so far */
  2530.                 bandIsDirty = true;
  2531.                 firstDirty = x;
  2532.                 }
  2533.             
  2534.             /* This is also the last dirty pixels so far */
  2535.             lastDirty = x;
  2536.             } // SetDirty
  2537.             
  2538.         /* If we have some dirty bits */
  2539.         if (bandIsDirty)
  2540.             {
  2541.             /* Move on to the next column */
  2542.             whichCol++;
  2543.             
  2544.             /* If this is a dirty column, then it is the last one so far */
  2545.             if (tempColumn != 0)
  2546.                 lastDirtyCol = whichCol;
  2547.             
  2548.             /* If we have a duplication, up the repeat count */
  2549.             if (tempColumn == lastColumn) // if (false) // turn off repeat groups
  2550.                 {
  2551.                 repeatCount++;
  2552.                 if (repeatCount == 14)
  2553.                     {
  2554.                     /* Kick out the old group */
  2555.                     whichCol -= 14;
  2556.                         EMITGROUP(pTheScanLine, kGraphicsCommand, whichCol);
  2557.                         numberBytesAdded += whichCol + kGroupSize;
  2558.                         pTheScanLine = (ScanLinePtr)(((Ptr) pTheScanLine) +
  2559.                             whichCol + kGroupSize);
  2560.                     
  2561.                     whichCol = 1;
  2562.                     lastDirtyCol = 1;
  2563.                     pTheScanLine->iTheData[0] = tempColumn;
  2564.                     }
  2565.                 }
  2566.             else
  2567.                 {
  2568.                 /* If we were repeating, emit the repeat group */
  2569.                 if (repeatCount >= 14)
  2570.                     {
  2571.                     EMITGROUP(pTheScanLine, kRepeatGroup, repeatCount);
  2572.                     numberBytesAdded += 1 + kGroupSize;
  2573.                     pTheScanLine = (ScanLinePtr) (((Ptr) pTheScanLine) + 
  2574.                         1 + kGroupSize);
  2575.                         
  2576.                     whichCol = 1;
  2577.                     lastDirtyCol = 1;
  2578.                     pTheScanLine->iTheData[0] = tempColumn;
  2579.                     }
  2580.                 repeatCount = 0;
  2581.                 lastColumn = tempColumn;
  2582.                 }
  2583.                 
  2584.             } // BandIsDirty
  2585.             
  2586.         } // end of loop for width of bitmap
  2587.  
  2588.     /* if we have a dirty band - emit the final bit of data we have
  2589.        packaged up */
  2590.     if (bandIsDirty)
  2591.         {            
  2592.         
  2593.         /* Set the margins to be the first and last dirty pixels in the scan line -
  2594.            the ImageWriter only does left margin optimization. */
  2595.         {
  2596.             SetMarginsPtr        marginBuffer;
  2597.             SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  2598.             
  2599.             check(hGlobals);
  2600.             
  2601.             /* Get the location for placing the set margin command */
  2602.             marginBuffer = (SetMarginsPtr) (buffer + (*bufferPos));
  2603.             
  2604.             /* Stuff in the set margin command */
  2605.             marginBuffer->cEscape  = ESCAPE;
  2606.             marginBuffer->cCommand = kSetMarginsCommand;
  2607.             
  2608.             /* convert left margin into ASCII and place it at the start of the buffer */
  2609.             Long2Dec((**hGlobals).leftMargin + firstDirty, (Ptr)(marginBuffer->cIndentDistance));
  2610.         }
  2611.         
  2612.         /* Send the last group command */
  2613.         if (repeatCount < 14)
  2614.             {
  2615.             /* Emit a normal group */
  2616.             EMITGROUP(pTheScanLine, kGraphicsCommand, lastDirtyCol);
  2617.             numberBytesAdded += lastDirtyCol + kGroupSize;
  2618.             }
  2619.         else
  2620.             {
  2621.             /* Don't stuff a final repeat group if it's blank space */
  2622.             if (tempColumn != 0)
  2623.                 {
  2624.                 /* Emit a repeat group */
  2625.                 EMITGROUP(pTheScanLine, kRepeatGroup, repeatCount);
  2626.                 numberBytesAdded += 1 + kGroupSize;
  2627.                 }
  2628.             } // end of repeatCount < 14
  2629.                     
  2630.         
  2631.         /*    Increment the count of the buffer by bytes added for groups, plus
  2632.             the header, if any, plus the set margins command */
  2633.         (*bufferPos) += numberBytesAdded + kScanLineSize + kSetMarginsSize;
  2634.  
  2635.         /* and put a <cr> at the end of the line */
  2636.         *(char*)(buffer + (*bufferPos)) = '\n';
  2637.         (*bufferPos) += 1;
  2638.         
  2639.         } // bandIsDirty
  2640.     else
  2641.         {
  2642.         // don't output data if we didn't have any!
  2643.         *bufferPos = originalBufferPos;
  2644.  
  2645.         // restore original number of line feeds
  2646.         pGlobals = *hGlobals;
  2647.         pGlobals->lineFeeds = originalLineFeeds;
  2648.         } // band is not dirty
  2649.         
  2650.     // always return your errors!
  2651. SendInitialLineFeeds:
  2652.     return(anErr);
  2653.     
  2654. } // SD_PackageBitmap
  2655.